---
title: "Replication for: Chiefs' Endorsements and Voter Behavior"
format: pdf
editor: visual
author:
    - Sarah Brierley^[Assistant Professor. London School of Economics. sabrierley@lse.ac.uk]
    - George K. Ofosu^[Assistant Professor. London School of Economics. g.ofosu@lse.ac.uk]
date: "`r format(Sys.Date(),'%B %d, %Y')`"
date-format: long
abstract: |
   \noindent 
link-citations: true
numbersections: no
geometry: margin=0.8in
header-includes:
  - \usepackage{setspace}
  - \usepackage{fullpage}
  - \usepackage{etoolbox}
  - \usepackage{longtable}
  - \usepackage{placeins}
  - \usepackage{tabu}
  - \usepackage{threeparttablex}
  - \usepackage{fvextra}
  - \usepackage[skip=8pt plus1pt]{parskip}
  - \makeatletter
  - \newcommand{\note}[1]{\textcolor{blue}{#1}}
  - \usepackage{fvextra}
  - \DefineVerbatimEnvironment{Highlighting}{Verbatim}{breaklines,commandchars=\\\{\}}
  - \usepackage{pdflscape}
  - \newcommand{\blandscape}{\begin{landscape}}
  - \newcommand{\elandscape}{\end{landscape}}
fontsize: 11pt
mainfont: Times New Roman
indent: true
execute: 
  eval: true
  echo: fenced
  output: false
  warning: false
  message: false
  error: false
---

\newpage

# Load required packages for codebook and replication of results

```{r}
#| label: load-packages
#| results: hide 


#Install/load pacman
if(!require(pacman)){install.packages("pacman");require(pacman)}

#Install/load required packages

p_load(xtable,stargazer, plyr, tidyverse, rio,kableExtra, 
       RColorBrewer,rgdal, maptools,rgeos,
       Rmisc,data.table,ggthemes,DiagrammeR,
       margins,ggpubr,mediation,
       broom,ggpubr,gridExtra,vtable,memisc)

```

# Codebook

```{r}
survey_data <- read_csv("replication_bo_chiefsurvey_masterdata.csv")
data <- data.set(survey_data)
names(data) <- names(survey_data)
class(data)


data <- within(data, {
description(instanceID)<- "Respondent ID"
description(age)<- "Respondent age"
description(female)<- "Respondent gender (female)"
description(primaryeduc_or_less)<- "Respondent education level (=primary education or less)"
description(agric_worker)<- "Employment type (= farmer)"
description(close_party)<- "Respondent reports being close to a political party"
description(close_to_npp)<- "Respondent report being close to the incumbent party (New Patriotic Party (NPP))"
description(npp_scale)<- "Feeling thermometer: how close respondent feel to the incumbent party (NPP)"
description(correct_chiefname)<- "Whether Respondent was able to correctly name traditional leader"
description(chief_performance_rate)<- "Respondent's rating of the chief's performance with traditional area with X months"
description(treatment)<- "Endorsement teatment"
description(turnout_int_2020)<- "Whether respondent intended to vote in the election"
description(vote_int_2020_endorsed_voters)<- "Respondent intend to vote for the endorsed candidate"
description(education)<- "Education level of respondent"
description(total_assets)<- "Total assets"
description(electoral_area)<- "Electoral area"
description(constituency)<- "Constituency"
description(turnout_actual_binary)<- "Respondent reported voting in the 2020 election"
description(vote_2020_endorsed)<- "Respondent voted for the endorsed in the 2020 elections"
description(like_nana)<- "How likeable do you think Nana Akufo-Addo is as a presidential candidate?"
description(trust_nana)<- "How trustworthy do YOU think Nana
Akufo-Addo is as a presidential candidate?"
description(agree_local_nana_rev)<- "How likely do you think it is that Nana Akuffo-Addo will do a good job at constructing new infrastructure in your local area?"
description(agree_national_nana_rev)<- "How likely do you think it is that Nana Akuffo-Addo will do a good job atworking in Accra to make good policies for the country"
description(ear_nana_rev)<- "How likely is it that [chief name] would have the listening ear of Nana Akufo-Addo if he were to be elected?"
description(devt_nana_rev)<- "How likely is it that [chief name] would be able to work with Nana Akufo-Addo to advance development in your local area?"
description(personal_nana_rev)<- "Should Nana Akufo-Addo win, how likely is it that [chief name] will provide more benefits to you personally or your family?"
description(fear)<- "Assuming that [chief name] did endorse a candidate, how fearful are you that if you do not vote for the candidate that [chief name] endorses you or your community will be disadvantaged?"
description(pettytrader)<- "Employment type (= petty trader)"
description(artisans)<- "Employment type (= artisan)"
description(close_to_ndc)<- "Respondent report being close to the incumbent party (New Patriotic Party (NPP))"
description(turnout_2016)<- "Respondent report voting in the 2016 presidential election"
description(asante)<- "Ethnicity: Asante"
description(bono)<- "Ethnicity: Bono"
description(dagati)<- "Ethnicity: Dagati"
description(ahafo)<- "Ethnicity: Ahafo"
description(ewe_anglo)<- "Ethnicity: Ewe/Anglo"
description(classify_code)<- "Respondents says 'Yes' to the question: 'Thinking back to the audio I just played to you, do you think it was an endorsement for Nana Akufo-Addo'"
description(trad_area)<- "Name of traditional area"
description(tribe)<- "Ethnic identity"
description(vote_2012)<- "Thinking back to the presidential election in 2012, which party's presidential candidate did you vote for?"
description(vote_2016)<- "Thinking back to the presidential election in 2016, which party's presidential candidate did you vote for?"
description(party_rating)<- "Scale of likability of the incumbent party vesus the opposition party"
description(partyid_cont)<- "Categorization of respondents to partisan groups according to party ratings"
description(know_chief_endorse)<- "To your knowledge, has ${chiefname} endorsed any of the presidential candidates for the upcoming election?"
description(know_endorse)<- "Which presidential candidate has ${chiefname} endorsed?"
description(hear_before)<- "Did you hear about the chiefs endorsement before I came to you today?"
description(hear_endorse1)<- "Where did you hear about the chief endorsing this candidate?"
description(psname)<- "Polling station name"
description(vote_nana)<- "In the election on December 7th, if you vote, how likely are you to vote in the Presidential election for Nana Akufo-Addo of the NPP?"
description(confirm_name)<- "Indicator for confirmed respondents in the second wave of survey"
description(close_party2)<- "Which party respondent is close to"
description(vote_int_2020) <- "I am going to show you a list of the political parties that are competing in the upcoming presidential elections.  Please take a look at the list.  Please click on the party that you would vote for if the upcoming presidential elections were held today.  You will be able to answer this question in private.  Remember, the survey is anonymous, so please feel free to answer honestly."
description(vote_actual1) <- "I am going to pass you the tablet. Please may you select the candidate you voted for in the presidential election?"

foreach(x=c(female,primaryeduc_or_less,agric_worker,close_party,close_to_npp,correct_chiefname,turnout_int_2020,vote_int_2020_endorsed_voters,turnout_actual_binary,vote_2020_endorsed,pettytrader,artisans,close_to_ndc,turnout_2016,asante,bono,dagati,ahafo,ewe_anglo,classify_code),{labels(x) <- c("Yes" = 1,                                              "No" = 0,                                            "Missing" = NA                                     )
    })

measurement(education) <- "ordinal"
labels (education)<- c( "No formal schooling" =1,
"Informal schooling only" = 2,
"Some primary schooling" = 3,
"Primary school completed (JHS)" =4, 
"Some secondary school (SHS)" = 5,
"Secondary school completed (SHS)" = 6,
"Some diploma or degree from polytechnic" = 7,
"Diploma or degree from a polytechnic completed" =8,
"Some university" = 9,
"University completed" = 10,
"Post-graduate completed" = 11, 
"Don't know" = 98,
"Refused to answer" = 99)

labels(know_chief_endorse) <- c("Yes" =1, "No" =2, "Don't know"= 98)
measurement(treatment) <- "nominal"
labels(treatment) <- c("Control" = "placebo", "Endorsement only"="onlyendorse", "Endorsement + rationale" = "full")
labels(know_endorse) <- c("Correct response"= 1, "Incorrect response"= 2, "Couldn't say name" = 99)

labels(hear_before) <- c("Yes" =1, "No" =2, "Don't know"= 98)


labels (tribe) <- c("Ahafo" =	4,
"Akuapem"=	30,
"Akyem"=	2,
"Asante"=1,
"Basari"=	29,
"Bassani"= 	14,
"Bimoba"=	16,
"Bono"=	3,
"Busanga"=	21,
"Dagati"=	23,
"Dagomba"	=12,
"Ewe/Anglo"=	9,
"Fante"=	5,
"Frafra" 	=25,
"Ga/Adangbe"	=10,
"Gonja"	=24,
"Grusi"=26,
"Guan" =	11,
"Hausa"= 	19,
"Kokomba"=	13,
"Kusasi"= 	27,
"Mamprusi"	=15,
"Mossi"	=20,
"Nabdam"=17,
"Sefwi"	=6,
"Sisaala"	= 22,
"Talensi" = 18,
"Wala"=	28,
"Wangara"	=31,
"Ghanaian only or doesn’t think of self in those terms" =	7,
"Other (please specify)"=	8,
"Don't know"	=98,
"Refused to answer"=	99)

foreach(x=c(vote_2012, vote_2016),{measurement(x) <- "nominal"  })

foreach(x=c(vote_2012, vote_2016),{labels(x) <- c("National Democratic Congress (NDC)" = 1, "New Patriotic Party (NPP)"= 2, "Convention People's Party (CPP)" = 3, "Progressive People's Party (PPP)" = 4, "Other" =5, "Did not vote in that election (too young)"= 96,    "Did not vote in that election (other reason)"= 97,  "Refused to answer"= 98, "Don't know"= 99 )
    })

labels(partyid_cont) <- c("NPP"= "NPP","NDC"="NDC", "MODERATE"="MODERATE")

labels(hear_endorse1) <- c("canvass"= "canvass", "friend"="friend", "myself"="myself", "other"="other", "radio"= "radio", "tv"="tv")

measurement(vote_nana) <- "ordinal"

measurement(confirm_name) <- "ordinal"

labels(confirm_name) <- c("Yes" =1, "No" =2)

labels(close_party2) <- c("National Democratic Congress (NDC)" = 1, "New Patriotic Party (NPP)"= 2, "Convention People's Party (CPP)" = 3, "Progressive People's Party (PPP)" = 4, "Other" =5, "Refused to answer"= 98, "Don't know"= 99 )

foreach(x= c(vote_int_2020,vote_actual1), {labels(x) <- c(
 	"NPP - Nana Addo Dankwa Akufo-Addo"=1,
	"NDC - John Dramani Mahama"=2,
"GUM - Christian Kwabena Andrews"=3,
	"CPP - Ivor Kobina Greenstreet"=4,
"GFP - Madam Akua Donkor"=5,
	"GCPP - Henry Herbert Lartey" = 6,
"APC - Hassan Ayariga" = 7, 
"LPG - Kofi Akpaloo" = 8,
"PNC - David Apasera" =9,
"PPP - Brigitte Dzogbenuku" =10,
	"NDP - Nana Konadu Agyeman-Rawlings" = 11,
"Independent candidate - Asiedu Walker" =12,
"I won't vote/I did not vote" = 13,  
	"Don't know"=99
)})

})



```

\newpage

```{r}
#| eval: true
#| results: markup
memisc::codebook(data)
```

\newpage

# Recoding of variables

## Wrangling of data

```{r}
#| label: load-wrangle-data
#| results: hide 


# read survey data
master <- readr::read_csv("replication_bo_chiefsurvey_masterdata.csv") 

# read data on respondents' distances from the chief's palace 

respdist <- readr::read_csv("respondents_location_withdist.csv")


#names(master)
master <- dplyr::left_join(master, respdist, by= "instanceID")

# Replace distance over 30km with NA's (seem)

master <- dplyr::mutate(master, dis_to_palace_KM= ifelse(dis_to_palace_KM>30, NA, dis_to_palace_KM))

# Calculate average distances to palace for each polling station 

ps_ave_resdist <- master%>%
  dplyr::group_by(psname)%>%
  dplyr::summarise(dis_to_palace_KM_psave = mean(dis_to_palace_KM,na.rm = T))


# Merge average distances to palace back into dataset
master <- dplyr::left_join(master, ps_ave_resdist)

master <- dplyr::mutate(master, dis_to_palace_KM_impt = ifelse(is.na(dis_to_palace_KM),dis_to_palace_KM_psave,dis_to_palace_KM))

## RECODING ----
# Add ID variable 
master <- setDT(master, keep.rownames = TRUE)[]

# Create binary treatment indicator (collapsing T2 and T3)
master$treatment_binary <- 1
master$treatment_binary[master$treatment=="placebo"] <- 0
#table(master$treatment_binary)

# Make placebo/control as reference category for treatment variable
master$treatment <- as_factor((master$treatment))
master <- within(master, treatment <- relevel(treatment, ref = "placebo"))

# Create vote dummies for 2012
master$vote_2012_ndc <- 0
master$vote_2012_ndc[master$vote_2012==1] <- 1
master$vote_2012_ndc[is.na(master$vote_2012)==TRUE] <- NA

master$vote_2012_npp <- 0
master$vote_2012_npp[master$vote_2012==2] <- 1
master$vote_2012_npp[is.na(master$vote_2012)==TRUE] <- NA

master$vote_2012_dnv <- 0
master$vote_2012_dnv[master$vote_2012==96] <- 1
master$vote_2012_dnv[master$vote_2012==97] <- 1
master$vote_2012_dnv[is.na(master$vote_2012)==TRUE] <- NA



# Create vote dummies for 2016
master$vote_2016_ndc <- 0
master$vote_2016_ndc[master$vote_2016==1] <- 1
master$vote_2016_ndc[is.na(master$vote_2016)==TRUE] <- NA

master$vote_2016_npp <- 0
master$vote_2016_npp[master$vote_2016==2] <- 1
master$vote_2016_npp[is.na(master$vote_2016)==TRUE] <- NA

master$vote_2016_dnv <- 0
master$vote_2016_dnv[master$vote_2016==96] <- 1
master$vote_2016_dnv[master$vote_2016==97] <- 1
master$vote_2016_dnv[is.na(master$vote_2016)==TRUE] <- NA

# Create party_rating cluster variable
#table(master$party_rating)

master$partyid_cluster <- NA
master$partyid_cluster[master$party_rating <= -5] <- "1. -7 to -5"
master$partyid_cluster[master$party_rating > -5 & master$party_rating <=-2] <- "2. -4 to -2"
master$partyid_cluster[master$party_rating > -2 & master$party_rating <=-1] <- "3. -1 to 1"
master$partyid_cluster[master$party_rating > 1 & master$party_rating <=4] <- "4. 2 to 4"
master$partyid_cluster[master$party_rating > 4] <- "5. 5 to 7"
master$partyid_cluster <- as.factor(master$partyid_cluster)

#table(master$partyid_cluster)

# Create party_rating cluster variable that collapses NDC/Moderate
#table(master$npp_scale)

master$party_cluster_collapse2 <- NA
master$party_cluster_collapse2[master$npp_scale <=2] <- "NDC/Moderate"
master$party_cluster_collapse2[master$npp_scale > 2] <- "NPP"
master$party_cluster_collapse2 <- as.factor(master$party_cluster_collapse2)

#table(master$party_cluster_collapse2)

master$party_cluster_collapse3 <- NA
master$party_cluster_collapse3[master$npp_scale <=3] <- "NDC/Moderate"
master$party_cluster_collapse3[master$npp_scale > 3] <- "NPP"
master$party_cluster_collapse3 <- as.factor(master$party_cluster_collapse3)

#table(master$party_cluster_collapse3)

# Recoded partyid_cont variable
master$partyid_cont_re <- NA
master$partyid_cont_re[master$partyid_cont == "NPP"] <- "1 NPP"
master$partyid_cont_re[master$partyid_cont == "MODERATE"] <- "2 MODERATE"
master$partyid_cont_re[master$partyid_cont == "NDC"] <- "3 NDC"
#table(master$partyid_cont_re)
master$partyid_cont_re <- NA
master$partyid_cont_re[master$partyid_cont == "NPP"] <- "1 NPP"
master$partyid_cont_re[master$partyid_cont == "MODERATE"] <- "2 MODERATE"
master$partyid_cont_re[master$partyid_cont == "NDC"] <- "3 NDC"
#table(master$partyid_cont_re)

# Party ID groups
## CREATE SEPARATE DATAFRAMES FOR PARTYID_CONT and PARTY_CLUSTER_COLLAPSE ----
## partyid_cont
## Full sample
data_full <- master

## NPP
data_npp <- master[master$partyid_cont == 'NPP',]

## NDC
data_ndc <- master[master$partyid_cont == 'NDC',]

## Moderate
data_moderate <- master[master$partyid_cont == 'MODERATE',]

## party_cluster_collapse 0-2 is NDC/Moderate
## NPP
data_collapse_npp2 <- master[master$party_cluster_collapse2=="NPP"]

## NDC/Moderate
data_collapse_ndc_moderate2 <- master[master$party_cluster_collapse2=="NDC/Moderate"]

## party_cluster_collapse 0-3 is NDC/Moderate
## NPP
data_collapse_npp3 <- master[master$party_cluster_collapse3=="NPP"]

## NDC/Moderate
data_collapse_ndc_moderate3 <- master[master$party_cluster_collapse3=="NDC/Moderate"]

## Rename variables ----
#master <- master %>%
  #dplyr::rename(dis_to_palace_KM = dis_to_palace_KM.x)

master <- dplyr::mutate(master, vote_nana_lk=ifelse(vote_nana > 7, NA, vote_nana))


##take out duplicates
master <- dplyr::filter(master,! duplicated(instanceID))

###Code for attrition
master <- dplyr::mutate(master, attrit = ifelse(is.na(confirm_name), 0, 1))

## different coding of partisanship
## NDC/other, NPP, not close to party

master <- dplyr::mutate(master, 
                        partyid_close_cat= factor(ifelse(close_party==0, "Unaligned",ifelse(close_party2==2,"NPP", ifelse(close_party2==1|close_party2>2 , "NDC", NA))), ordered = FALSE),
                        partyid_cat_hist = factor(ifelse(vote_2012==1 & vote_2016==1,"NDC",ifelse(vote_2012==2 & vote_2016==2,"NPP", ifelse(vote_2012==96|vote_2012==97|vote_2012==98|vote_2012==99,NA, "Swing/minor" ))),ordered = FALSE),
                        like_trust_nana = round(7*(like_nana+ trust_nana)/14) 
                        )

```

## Descriptive statistics of treatment assignment and attrition

```{r}

#| label: treatment-cond-att
#| results: asis 


#Table 2: Treatment conditions


tr_tab_a <- master%>%
  dplyr::count(treatment,sort = T)%>%
  dplyr::mutate(Proportion = n/sum(n))


full <- tibble(treatment="Total", n=sum(tr_tab_a$n),Proportion=1)

tr_tab_a <- bind_rows(tr_tab_a,full)

tr_tab_ab <- bind_rows(tr_tab_a[1,],tr_tab_a[3,],tr_tab_a[2,],tr_tab_a[4,] )

tr_wv2 <- master%>%
  dplyr::group_by(treatment)%>%
  dplyr::summarise(n_wave2= sum(attrit))%>%dplyr::mutate(Proportion_W2 = n_wave2/sum(n_wave2))

tr_wv2 <- bind_rows(tr_wv2, tibble(treatment="Total", n_wave2=sum(tr_wv2$n_wave2),Proportion_W2=1))

tr_tab_ab <- dplyr::left_join(tr_tab_ab,tr_wv2)%>%
  dplyr::mutate(`Attrition rate`= (n-n_wave2)/n)


tr_tab_ab %>%
  dplyr::mutate(varlab= c("Control", "Endorsement (A)", "Endorsement (A) + rationale (B)", "Total"))%>%
  dplyr::select(varlab, n: `Attrition rate`)%>%
  kbl(caption= "Treatment conditions", digits = 3,col.names = c("Treatment condition", "# Resp.", "Prop.","# Resp.", "Prop.", "Attrition rate"),booktabs = T,label = "tr_sum") %>%
    add_header_above(c(" " = 1, "Wave 1" = 2, "Wave 2" = 2, " " = 1))%>%
  kable_classic(full_width = T, html_font = "Cambria",font_size = 9)%>%column_spec(1, width = "14em")
```

\FloatBarrier

## Descriptive statistics of respondents

\indent

```{r}

#| label: load-wrangle-data
#| results: asis 



#Table 3 : Descriptive statistics of respondents

resp_char <- master%>%dplyr::select(age, female,primaryeduc_or_less, agric_worker,close_party, close_to_npp,npp_scale, correct_chiefname,dis_to_palace_KM_impt,chief_performance_rate)%>% 
  dplyr::mutate(app_chief =ifelse(is.na(chief_performance_rate), NA, ifelse(chief_performance_rate>3,1,0)))%>%
psych::describe(fast = TRUE) %>%
  as_tibble(rownames="rowname")%>%
  dplyr::select(rowname,mean,sd,n)

resp_char %>%
  dplyr::mutate(varlab= c("Age", "Gender (Female=1)", "Education (Primary or less =1)", "Employment (Farming=1)", "Feel close to a party","Feel close to the incumbent party ( NPP)","Closeness to incumbent party on Likert scale (0--7)","Correctly name chief", "Distance to chief's palace (KMs)","Approval of chief performance (0-7)","Approve of chief (4-7)"))%>%
  dplyr::select(varlab, mean,sd,n)%>%
  kbl(caption= "Descriptive statistics of respondents", digits = 3,col.names = c("Variable", "Mean", "Std. Dev.","N"),booktabs = T,label = "desc_stat") %>%
  kable_classic(full_width = T,font_size = 10)%>%
  column_spec(1, width = "25em")%>%
  pack_rows("Demography", 1,4)%>%
  pack_rows("Partisanship", 5,7)%>%
  pack_rows("Chieftaincy", 8,11)

```

# Main results

```{r}

#| label: main-results
#| results: asis 
#| message: FALSE
#| echo: true
#| eval: true
#| warning: true


# data analysis for main results 


## select data for pre-election survey results

trydat_pr <- master%>%
  dplyr::select(turnout_int_2020,vote_int_2020_endorsed_voters,treatment_binary,treatment,age, education, total_assets, npp_scale, electoral_area, party_cluster_collapse3,vote_nana_lk,dis_to_palace_KM_impt,constituency)%>%
  dplyr::mutate(party_cluster_collapse3 = relevel(party_cluster_collapse3, "NPP"),
         age_cat = factor(ifelse(age >= 18 & age <=35, 1, ifelse(age >= 36 & age <= 55,2,3))),
         dist_cat= factor(ifelse(dis_to_palace_KM_impt <=5,2, ifelse(dis_to_palace_KM_impt >5 &dis_to_palace_KM_impt <=10, 1, 0))),
         treatment_endorseonly_ref = relevel(treatment, "onlyendorse")
         )

## select data for post-election survey results


  
trydat_post <- master%>%
  dplyr::select(turnout_actual_binary, vote_2020_endorsed,treatment_binary,treatment,age, education, total_assets, npp_scale, electoral_area, party_cluster_collapse3,dis_to_palace_KM_impt,constituency)%>%
  mutate(party_cluster_collapse3 = relevel(party_cluster_collapse3, "NPP"),
         age_cat = factor(ifelse(age >= 18 & age <=35, 1, ifelse(age >= 36 & age <= 55,2,3))),
         dist_cat= factor(ifelse(dis_to_palace_KM_impt <=5,2, ifelse(dis_to_palace_KM_impt >5 &dis_to_palace_KM_impt <=10, 1, 0 ))),
         treatment_endorseonly_ref = relevel(treatment, "onlyendorse")
         )




## generate difference in means estimates using OLS


## Full sample (any treatment)
### pre-election survey
h2_intention_full_no_controls <- lm(vote_int_2020_endorsed_voters ~ treatment_binary, data=trydat_pr)

h2_intention_full_controls <- lm(vote_int_2020_endorsed_voters ~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=trydat_pr)

### post election survey

h2_actual_full_no_controls <- lm(vote_2020_endorsed ~ treatment_binary, data=trydat_post)
h2_actual_full_controls <- lm(vote_2020_endorsed ~ treatment_binary + age + education + total_assets + npp_scale + as.factor(electoral_area), data=trydat_post)




## Full sample (treatment type)

## pre-election survey
h2_1_2 <- lm(vote_int_2020_endorsed_voters ~ treatment, data=trydat_pr)

h2_1_2_controls <- 
lm(vote_int_2020_endorsed_voters ~ treatment + age + education + total_assets + npp_scale + electoral_area, data=trydat_pr)


## post election-survey
h2_1_2_actual <- lm(vote_2020_endorsed ~ treatment, data=trydat_post)


h2_1_2_actual_controls <- lm(vote_2020_endorsed ~ treatment + age + education + total_assets + npp_scale + as.factor(electoral_area), data=trydat_post)



##------ note for deletion if no longer needed
###Change reference category for different treatments

h2_1_2b <- lm(vote_int_2020_endorsed_voters ~ treatment_endorseonly_ref, data=trydat_pr)

h2_1_2_controlsb <- 
lm(vote_int_2020_endorsed_voters ~ treatment_endorseonly_ref + age + education + total_assets + npp_scale + electoral_area, data=trydat_pr)

h2_1_2_actualb <- lm(vote_2020_endorsed ~ treatment_endorseonly_ref, data=trydat_post)


h2_1_2_actual_controlsb <- lm(vote_2020_endorsed ~ treatment_endorseonly_ref + age + education + total_assets + npp_scale + as.factor(electoral_area), data=trydat_post)

## 

itt_estimates <- tibble(rowname= c("itt_pre_vote", "itt_post_vote"),group1=as.character(2), 
                        itt = c(summary(h2_intention_full_controls)$coefficients[2,1], summary(h2_actual_full_controls)$coefficients[2,1]),  
                        itt_se=c(summary(h2_intention_full_controls)$coefficients[2,2], summary(h2_actual_full_controls)$coefficients[2,2]))







```

```{r}



#| label: main-mns
#| results: asis 
#| message: FALSE
#| echo: true
#| eval: true
#| warning: true


# Generate summary statistics for plotting estimates

main_outsum_pr <- trydat_pr%>%
  dplyr::select(vote_int_2020_endorsed_voters)%>%
  psych::describeBy(group = trydat_pr$treatment_binary,mat = TRUE)%>%
  as_tibble(rownames="rowname")%>%
  dplyr::select(rowname,n,group1,mean,se)


main_outsum_post <- trydat_post%>%
  dplyr::select(vote_2020_endorsed)%>%
  psych::describeBy(group = trydat_post$treatment_binary,mat = TRUE)%>%
  as_tibble(rownames="rowname")%>%
  dplyr::select(rowname,n,group1,mean,se)


mainrestab <- dplyr::bind_rows(main_outsum_pr,main_outsum_post,itt_estimates)

mainrestab <- mutate(mainrestab, y_points=ifelse(group1=="0"|group1=="2", 1, 2),estimate_type=ifelse(group1=="0"|group1=="1", "Group means", "ITT"),  Wave=factor( c(rep("Pre-election",2), rep("Post-election",2), "Pre-election", "Post-election"), levels = c("Pre-election", "Post-election"),ordered = TRUE), type=c( "Vote", "Vote", "Vote", "Vote", "Vote", "Vote"))


```

```{r}

#| label: main-vote
#| results: asis 
#| message: FALSE
#| echo: true
#| eval: true
#| warning: true
#|fig.align: center 
#|fig.height: 9
#|fig.width: 11
#|fig.cap: 'Average intention-to-treat effect of chiefly endorsement on vote choice'


## formatting for plots

plottheme <- theme(axis.title = element_text(face = "bold",size = 18,colour = "black"),legend.title = element_text(face = "bold"),panel.background =element_blank(),panel.border = element_rect(size = 2,fill = NA),legend.key =element_rect(fill = "white"),axis.ticks = element_line(size = 2),axis.line = element_line(size = 1, linetype = "solid"),axis.line.y.right=element_line(size = 2, linetype = "solid"), title = element_text(family = "serif",size=16,colour = "black",face = "bold"),axis.text.y = element_text(family = "serif",size=16,colour = "black"),axis.text.x = element_text(family = "serif",size=16,colour = "black"),legend.text = element_text(size = 16),strip.text.x = element_text(size = 18, face = "bold"),panel.grid.major.y = element_line(colour="gray", size=0.5),panel.grid.major.x = element_line(colour="gray", size=0.5),panel.spacing = unit(2, "lines"))


## 

p3 <- ggplot(filter(mainrestab, type=="Vote"&estimate_type=="Group means"),mapping = aes(x=mean, y=y_points))+
  geom_point(size=5)+
  geom_errorbar(mapping=aes(y=y_points, xmin=mean -1.96*se, xmax=mean+1.96*se),size=1,width=.01)+
  scale_y_continuous(breaks=c(1, 2),labels = c( "Control", "Treatment"),limits = c(0.5,2.2))+
  #scale_x_continuous(limits = c(-0.05,1))+
  labs(x ="Proportion of respondents voting for endorsed candidate", y="Treatment condition", title= "Panel A")+
  theme_tufte()+
  plottheme +
  facet_wrap(~Wave,ncol = 2)



p4 <- ggplot(filter(mainrestab, type=="Vote"&estimate_type=="ITT"),mapping = aes(x=itt, y=y_points))+
  geom_point(size=5)+
  geom_errorbar(mapping=aes(y=y_points, xmin=itt -1.96*itt_se, xmax=itt +1.96*itt_se),size=1,width=.01)+
  scale_y_continuous(breaks=c(1),labels = c( "Treatment"),limits = c(0.5,1.5))+
  geom_vline(xintercept =0,size=0.8,linetype=2,color="black")+
  #scale_x_continuous(limits = c(-0.05,1))+
  labs(x ="Average ITT effect", y="", title = "Panel B")+
  theme_tufte()+
   plottheme +
  facet_wrap(~Wave,ncol = 2)+theme(strip.text.x = element_blank(),axis.text.y =element_text(colour = "white"))


gt2 <- arrangeGrob(p3, p4, ncol = 1)
as_ggplot(gt2)

```

## Heterogeneous effects by partisanship and prior approval of chief

```{r}

#| label: main-results
#| results: asis 


## partisanship is coded here to imply whether you are close to a party or not/ and if so, which party


dat_pr_rb <- master%>%
  dplyr::select(turnout_int_2020,vote_int_2020_endorsed_voters,treatment_binary,treatment,age, education, total_assets, npp_scale, electoral_area,vote_nana_lk,dis_to_palace_KM_impt,constituency,partyid_close_cat,partyid_cat_hist,chief_performance_rate)%>%
  dplyr::mutate(partyid_close_cat = relevel(partyid_close_cat, "NPP"),partyid_cat_hist = relevel(partyid_cat_hist, "NPP"),
         age_cat = factor(ifelse(age >= 18 & age <=35, 1, ifelse(age >= 36 & age <= 55,2,3))),
         dist_cat= factor(ifelse(dis_to_palace_KM_impt <=5,2, ifelse(dis_to_palace_KM_impt >5 &dis_to_palace_KM_impt <=10, 1, 0))),
         npp_scale_cat = relevel(factor(ifelse(is.na(npp_scale), NA, ifelse(npp_scale==0|npp_scale==1, "NDC", ifelse(npp_scale==6|npp_scale==7, "NPP", "Moderate")))),"NPP"),
         app_chief =ifelse(is.na(chief_performance_rate), NA, ifelse(chief_performance_rate>3,1,0))
         )
         
dat_post_rb <- master%>%
  dplyr::select(turnout_actual_binary, vote_2020_endorsed,treatment_binary,treatment,age, education, total_assets, npp_scale, electoral_area,dis_to_palace_KM_impt,constituency,partyid_close_cat,partyid_cat_hist,chief_performance_rate)%>%
  mutate(partyid_close_cat = relevel(partyid_close_cat, "NPP"),partyid_cat_hist = relevel(partyid_cat_hist, "NPP"),
         age_cat = factor(ifelse(age >= 18 & age <=35, 1, ifelse(age >= 36 & age <= 55,2,3))),
         dist_cat= factor(ifelse(dis_to_palace_KM_impt <=5,2, ifelse(dis_to_palace_KM_impt >5 &dis_to_palace_KM_impt <=10, 1, 0 ))),
         npp_scale_cat = relevel(factor(ifelse(is.na(npp_scale), NA, ifelse(npp_scale==0|npp_scale==1, "NDC", ifelse(npp_scale==6|npp_scale==7, "NPP", "Moderate")))), "NPP"),
         app_chief =ifelse(is.na(chief_performance_rate), NA, ifelse(chief_performance_rate>3,1,0))
         )


## regression estimates for pre-election estimates:

h2part_rb <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*partyid_close_cat, data=dat_pr_rb)

h2part_c_rb <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*partyid_close_cat + age + education + total_assets + electoral_area, data=dat_pr_rb)

#### estimate marginal effects

h2part_c_m_rb <- margins::margins(h2part_c_rb,data=data.frame(dat_pr_rb), at = list("partyid_close_cat" =c("NPP","NDC", "Unaligned")))


sumtab_rb <- summary(h2part_c_m_rb)[summary(h2part_c_m_rb)$factor=="treatment_binary", c("partyid_close_cat","AME","SE","p")]

## regression estimates for post-election estimates:


h2actual_rb <- lm(vote_2020_endorsed ~ treatment_binary*partyid_close_cat, data=dat_post_rb)

h2actual_c_rb <- lm(vote_2020_endorsed ~ treatment_binary*partyid_close_cat + age + education + total_assets+ electoral_area, data=dat_post_rb)

h2actual_c_m_rb <- margins::margins(h2actual_c_rb,data=data.frame(dat_post_rb), at = list("partyid_close_cat" =c("NPP","NDC", "Unaligned")))


sumtab1_rb <- summary(h2actual_c_m_rb)[summary(h2actual_c_m_rb)$factor=="treatment_binary", c("partyid_close_cat","AME","SE","p")]

```

```{r}

#| label: mainparty-rb1
#| results: asis 
#|fig.align: center 
#|fig.height: 9
#|fig.width: 11
#|fig.cap: 'Average marginal effect of chiefly endorsement on vote choice by partisanship'


tab_party_het_rb1 = bind_rows(sumtab_rb,sumtab1_rb)%>%
  dplyr::mutate(Period= factor(c("Pre-election", "Pre-election","Pre-election", "Post-election", "Post-election","Post-election"), levels = c("Pre-election", "Post-election"), ordered = TRUE),point=c(0.9,1.9,2.9,1.1,2.1,3.1))

ggplot(tab_party_het_rb1,mapping = aes(x=point, y=AME, shape=Period))+
  geom_point(size=4)+
  geom_errorbar(mapping=aes(x=point, ymin=AME -1.96*SE, ymax=AME+1.96*SE),size=1,width=.01)+
  scale_x_continuous(breaks=c(1,2,3),labels = c("Incumbent", "Opposition", "Unaligned"),limits = c(0.5,3.5))+
  scale_y_continuous(limits = c(-0.15,0.25))+
  geom_hline(yintercept = 0,linetype=2, color="black")+
  geom_vline(xintercept = c(1.5,2.5),linetype=2, color="grey",size=1.3)+
  labs(x ="Which party are you close to?", y="Average marginal effect of chiefly endorsement")+
  theme_tufte()+
  plottheme
```

```{r}


#| label: chief-approval
#| results: asis 




trydat_pr_chap <- master%>%
  dplyr::select(turnout_int_2020,vote_int_2020_endorsed_voters,treatment_binary,treatment,age, education, total_assets, npp_scale, electoral_area, party_cluster_collapse3,vote_nana_lk,dis_to_palace_KM_impt,constituency,chief_performance_rate)%>%
  mutate(party_cluster_collapse3 = relevel(party_cluster_collapse3, "NPP"),
         age_cat = factor(ifelse(age >= 18 & age <=35, 1, ifelse(age >= 36 & age <= 55,2,3))),
         dist_cat= factor(ifelse(dis_to_palace_KM_impt <=5,2, ifelse(dis_to_palace_KM_impt >5 &dis_to_palace_KM_impt <=10, 1, 0))),app_chief =ifelse(is.na(chief_performance_rate), NA, ifelse(chief_performance_rate>3,1,0))
)
 
trydat_post_chap <- master%>%
  dplyr::select(turnout_actual_binary, vote_2020_endorsed,treatment_binary,treatment,age, education, total_assets, npp_scale, electoral_area, party_cluster_collapse3,dis_to_palace_KM_impt,constituency,chief_performance_rate)%>%
  mutate(party_cluster_collapse3 = relevel(party_cluster_collapse3, "NPP"),
         age_cat = factor(ifelse(age >= 18 & age <=35, 1, ifelse(age >= 36 & age <= 55,2,3))),
         dist_cat= factor(ifelse(dis_to_palace_KM_impt <=5,2, ifelse(dis_to_palace_KM_impt >5 &dis_to_palace_KM_impt <=10, 1, 0 ))),
         app_chief =ifelse(is.na(chief_performance_rate), NA, ifelse(chief_performance_rate>3,1,0)) )

#dim(trydat_pr)
trydat_pr_chap <- na.omit(trydat_pr_chap)
#dim(trydat_pr_chap)

#dim(trydat_post)
trydat_post_chap <- na.omit(trydat_post_chap)
#dim(trydat_post_chap)



## OLS estimates for treatment effects by respondent's approval of chief's performance


### pre-election estimates
h2chap <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*app_chief, data=trydat_pr_chap)
h2chap_c <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*app_chief + age + education + total_assets + electoral_area, data=trydat_pr_chap)


h2chap_c_m <- margins::margins(h2chap_c,data=data.frame(trydat_pr_chap), at = list("app_chief" =c(0,1)))
sumtab_chap <- summary(h2chap_c_m)[summary(h2chap_c_m)$factor=="treatment_binary", c("app_chief","AME","SE","p")]

### post-election estimates

h2chap_actual <- lm(vote_2020_endorsed ~ treatment_binary*app_chief, data=trydat_post_chap)
h2chap_actual_c <- lm(vote_2020_endorsed ~ treatment_binary*app_chief + age + education + total_assets+ electoral_area, data=trydat_post_chap)


h2chap_actual_c_m <- margins::margins(h2chap_actual_c,data=data.frame(trydat_post_chap), at = list("app_chief" =c(0,1)))
sumtab1_chap1 <- summary(h2chap_actual_c_m)[summary(h2chap_actual_c_m)$factor=="treatment_binary", c("app_chief","AME","SE","p")]

```

```{r, results='asis', message=FALSE,echo=FALSE, eval=TRUE, warning=FALSE,fig.align='center', fig.height=6, include=TRUE}


# interacting chief's approval with partisanship

h2part_rb_capp <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*partyid_close_cat*app_chief, data=dat_pr_rb)

h2part_c_rb_capp <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*partyid_close_cat*app_chief + age + education + total_assets + electoral_area, data=dat_pr_rb)

h2part_c_m_rb_capp <- margins::margins(h2part_c_rb_capp,data=data.frame(dat_pr_rb), at = list("partyid_close_cat" =c("NPP","NDC", "Unaligned"), "app_chief" =c(0,1)))


sumtab_rb_capp <- summary(h2part_c_m_rb_capp)[summary(h2part_c_m_rb_capp)$factor=="treatment_binary", c("partyid_close_cat","app_chief","AME","SE","p")]



h2actual_rb_capp <- lm(vote_2020_endorsed ~ treatment_binary*partyid_close_cat*app_chief, data=dat_post_rb)

h2actual_c_rb_capp <- lm(vote_2020_endorsed ~ treatment_binary*partyid_close_cat*app_chief + age + education + total_assets+ electoral_area, data=dat_post_rb)


h2actual_c_m_rb_capp <- margins::margins(h2actual_c_rb_capp,data=data.frame(dat_post_rb), at = list("partyid_close_cat" =c("NPP","NDC", "Unaligned"), "app_chief" =c(0,1)))


sumtab1_rb_capp <- summary(h2actual_c_m_rb_capp)[summary(h2actual_c_m_rb_capp)$factor=="treatment_binary", c("partyid_close_cat","app_chief","AME","SE","p")]

```

```{r}

#| label: chief-approval-partyrb
#| results: asis 
#|fig.align: center 
#|fig.height: 12
#|fig.width: 18
#|fig.cap: 'Average marginal effect of chiefly endorsement by partisanship and evaluation of chief'


tab_party_hetchief_rb = bind_rows(sumtab_rb_capp,sumtab1_rb_capp)%>%
  dplyr::mutate(Period= factor( c(rep("Pre-election",6),rep("Post-election",6)), levels = c("Pre-election", "Post-election"), ordered = TRUE),point=c(0.9,1.9,0.9,1.9,0.9,1.9,1.1,2.1,1.1,2.1,1.1,2.1), label=factor( ifelse(partyid_close_cat=="Unaligned","Unaligned",ifelse(partyid_close_cat=="NPP","Incumbent", "Opposition")), levels = c("Incumbent", "Opposition", "Unaligned"), ordered = FALSE))


ggplot(tab_party_hetchief_rb,mapping = aes(x=point, y=AME, shape=Period))+
  geom_point(size=4)+
  geom_errorbar(mapping=aes(x=point, ymin=AME -1.96*SE, ymax=AME+1.96*SE),size=2,width=.01)+
  scale_x_continuous(breaks=c(1, 2),labels = c("Disapprove", "Approve"),limits = c(0.5,2.5))+
  scale_y_continuous(limits = c(-0.2,0.35))+
  geom_hline(yintercept = 0,linetype=2, color="black")+
  geom_vline(xintercept = 1.5,linetype=2, color="grey",size=1.3)+
  labs(x ="Assessment of chief", y="Average marginal effect of chiefly endorsement")+
  theme_tufte()+
  plottheme+
  facet_wrap(~label)

```

```{r}

#| label: tab-chief-approval-partyrb
#| results: asis 
#| include: false






## check, which table this is in paper


stargazer::stargazer(h2part_rb_capp,h2part_c_rb_capp, h2actual_rb_capp,h2actual_c_rb_capp,
  #font.size="footnotesize",
  type = "latex",
  title = "",
  #column.labels = c("Model A", "Model B", "Model C", "Model D"),
  dep.var.caption  = "Voted for endorsed",
  dep.var.labels = c("Pre-election","Post-election"),
    covariate.labels = c("Treatment", "Close to NDC", "Close to no party","Approve of chief", "Treatment x Close to NDC", "Treatment x Close to no party","Treatment x Approve of chief","Close to NDC x Approve of chief", "Close to no party x Approve of chief", "Treatment x Close to NDC x Approve of chief", "Treatment x Close to no party x Approve of chief"),

  add.lines = list(c("EA fixed effects", rep(c("No","Yes"),2)),c("Controls", rep(c("No","Yes"),2))),
  multicolumn = T,
  omit = c("age", "education","total_assets", "electoral_area"),
  keep.stat = c("n","rsq"),
  notes.align = "l",
  style = "apsr",
  label="het_party_approve_rb1",
  header=F
  )
```

# Mechanisms

## Does the rationale for the endorsement matter?

```{r }

#| label: treatment-decomposition
#| results: asis 
#| message: false
#| echo: true
#| eval: true
#| warning: true
#| include: true


## decompose effects by treatment type among unaligned voters

### pre-election period
h2party_tcomp <- lm(vote_int_2020_endorsed_voters ~ treatment, data=dplyr::filter(master, partyid_close_cat=="Unaligned"))

h2party_tcomp_c <- lm(vote_int_2020_endorsed_voters ~ treatment + age + education + total_assets + electoral_area, data=dplyr::filter(master, partyid_close_cat=="Unaligned"))

#### post-election period

h2actual_tcomp <- lm(vote_2020_endorsed ~ treatment, data=dplyr::filter(master, partyid_close_cat=="Unaligned"))

h2actual_tcomp_c <- lm(vote_2020_endorsed ~ treatment+ age + education + total_assets + electoral_area, data=dplyr::filter(master, partyid_close_cat=="Unaligned"))

mechtab_trpart <-as_tibble( rbind(summary(h2party_tcomp_c)$coef[c(2,3), c(1,2,4)],summary(h2actual_tcomp_c)$coef[c(2,3), c(1,2,4)]))

mechtab_trpart <- dplyr::mutate(mechtab_trpart, points=c(0.9, 1.9, 1.1, 2.1), Period=factor(c("Pre-election","Pre-election", "Post-election", "Post-election"),levels = c("Pre-election", "Post-election"), ordered = TRUE), Treatment= factor(c("Endorsement only", "Endorsement + rationale","Endorsement only", "Endorsement + rationale"), levels = c("Endorsement only", "Endorsement + rationale")) , points2=c(0.9,1.1, 1.9, 2.1))



# stargazer::stargazer(h2party_tcomp,h2party_tcomp_c, h2actual_tcomp,h2actual_tcomp_c,
#   #font.size="footnotesize",
#   type = "latex",
#   title = "ITT effect of chiefly endorsement type on vote choice by treatment type",
#   #column.labels = c("Model A", "Model B", "Model C", "Model D"),
#   dep.var.caption  = "Voted for endorsed",
#   dep.var.labels = c("Pre-election","Post-election"),
#     covariate.labels = c("Endorsement only", "Endorsement + rationale"),
# 
#   add.lines = list(c("EA fixed effects", rep(c("No","Yes"),2)),c("Controls", rep(c("No","Yes"),2))),
#   multicolumn = T,
#   omit = c("age", "education","total_assets", "electoral_area"),
#   keep.stat = c("n","rsq"),
#   notes.align = "l",
#   style = "apsr",
#   label="unaligned",
#   header=F
#   )




```

```{r mech-tr-parts, results='asis', message=FALSE,echo=FALSE, eval=TRUE, warning=FALSE,fig.align='center', fig.height=6, fig.width= 10, fig.cap= "Average ITT effect of chiefly endorsement on vote choice among opposing voters by treatment type"}


#| label: mech-tr-parts
#| results: asis 
#| message: false
#| echo: true
#| eval: true
#| warning: true
#| include: false
#|fig.align: center 
#|fig.height: 6
#|fig.width: 10
#|fig.cap: 'Average ITT effect of chiefly endorsement on vote choice among opposing voters by treatment type'

ggplot(mechtab_trpart,mapping = aes(x=points2, y=Estimate, shape=Treatment))+
  geom_point(size=4)+
  geom_errorbar(mapping=aes(x=points2, ymin=Estimate -1.96*`Std. Error`, ymax=Estimate+1.96*`Std. Error`),size=1,width=.01)+
  scale_x_continuous(breaks=c(1, 2),labels = c("Pre-election", "Post-election"),limits = c(0.5,2.5))+
  scale_y_continuous(limits = c(-0.2,0.35))+
  geom_hline(yintercept = 0,linetype=2, color="black")+
  geom_vline(xintercept = 1.5,linetype=2, color="grey",size=1.3)+
  labs(x ="Election period", y="Average ITT effect")+
  theme_tufte()+
  plottheme


```

## Effect on intermediate variables and causal mediation analyses

```{r}

#| label: mech-mediation
#| results: asis 


mechdat_pr <- master%>%
  dplyr::select(like_nana,trust_nana,agree_local_nana_rev,agree_national_nana_rev,ear_nana_rev,devt_nana_rev,personal_nana_rev, fear, treatment_binary,treatment,age, education, total_assets, npp_scale, electoral_area, party_cluster_collapse3,like_trust_nana,partyid_close_cat)%>%
  mutate(party_cluster_collapse3 = relevel(party_cluster_collapse3, "NPP"),
         age_cat = factor(ifelse(age >= 18 & age <=35, 1, ifelse(age >= 36 & age <= 55,2,3)))
         )

         
#dim(mechdat_pr)
mechdat_pr <- na.omit(mechdat_pr)
#dim(mechdat_pr)




## Simple difference in means Table

## summary statistics
#like_nana,trust_nana,

mech_outsum_pr <- mechdat_pr%>%
  filter(partyid_close_cat=="Unaligned")%>%
  dplyr::select(treatment_binary,like_trust_nana, agree_local_nana_rev,agree_national_nana_rev,ear_nana_rev,devt_nana_rev,personal_nana_rev, fear)%>%
  psych::describeBy(group ="treatment_binary",mat = TRUE)%>%
  as_tibble(rownames="rowname")%>%
  dplyr::select(rowname,n,group1,mean,se)


sum_stats_grp_bind <- cbind(mech_outsum_pr[mech_outsum_pr$group1==0, c( "mean", "se")], mech_outsum_pr[mech_outsum_pr$group1==1, c("mean", "se")])

### Disaggregate by treatment type

mech_outsum_pr_DT <- mechdat_pr%>%
  filter(partyid_close_cat=="Unaligned")%>%
  dplyr::select(treatment,like_trust_nana, agree_local_nana_rev,agree_national_nana_rev,ear_nana_rev,devt_nana_rev,personal_nana_rev, fear)%>%
  psych::describeBy(group ="treatment",mat = TRUE)%>%
  as_tibble(rownames="rowname")%>%
  dplyr::select(rowname,n,group1,mean,se)


sum_stats_grp_bind_DT <- cbind(mech_outsum_pr_DT[mech_outsum_pr_DT$group1=="placebo", c( "mean", "se")], mech_outsum_pr_DT[mech_outsum_pr_DT$group1=="onlyendorse", c("mean", "se")], mech_outsum_pr_DT[mech_outsum_pr_DT$group1=="full", c("mean", "se")])



##pre-election: difference in means with binary treatment

md1 <- lm(like_trust_nana~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,partyid_close_cat=="Unaligned"))

#md2 <- lm(trust_nana~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,party_cluster_collapse3 !="NPP"))

md3 <- lm(agree_local_nana_rev~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,partyid_close_cat=="Unaligned"))

md4 <- lm(agree_national_nana_rev~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,partyid_close_cat=="Unaligned"))

md5 <- lm(ear_nana_rev~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,partyid_close_cat=="Unaligned"))

md6 <- lm(devt_nana_rev~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,partyid_close_cat=="Unaligned"))

md7 <- lm(personal_nana_rev~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,partyid_close_cat=="Unaligned"))

md8 <- lm(fear~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,partyid_close_cat=="Unaligned"))

mechtab <- rbind(summary(md1)$coef[2, c(1,2,4)],summary(md3)$coef[2, c(1,2,4)],summary(md4)$coef[2, c(1,2,4)],summary(md5)$coef[2, c(1,2,4)],summary(md6)$coef[2, c(1,2,4)],summary(md7)$coef[2, c(1,2,4)],summary(md8)$coef[2, c(1,2,4)])


#summary(md2)$coef[2, c(1,2,4)],

mechtab_main <- cbind(sum_stats_grp_bind[-1,],mechtab)

colnames(mechtab_main) <- c("Mean in control", "SE in control", "Mean in treatment", "SE in tr", "Estimated ITT","SE_itt", "P-value")


mechtab_main <- mechtab_main%>%
  as_tibble()%>%
  dplyr::mutate(var= c("Personal quality (likable and trustworthy)", "Bring local development", "National policy","Listening ear of endorsed","Work well with endorsed for local development", "Chief can provide private benefits","Fear of personal or community disadvantage"))%>%
  dplyr::select(var,`Mean in control`:`P-value`)


## disaggregated by treatment groups


md1_dt <- lm(like_trust_nana~ treatment + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,partyid_close_cat=="Unaligned"))


md3_dt <- lm(agree_local_nana_rev~ treatment + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,partyid_close_cat=="Unaligned"))

md4_dt <- lm(agree_national_nana_rev~ treatment + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,partyid_close_cat=="Unaligned"))

md5_dt <- lm(ear_nana_rev~ treatment + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,partyid_close_cat=="Unaligned"))

md6_dt <- lm(devt_nana_rev~ treatment + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,partyid_close_cat=="Unaligned"))

md7_dt <- lm(personal_nana_rev~ treatment + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,partyid_close_cat=="Unaligned"))

md8_dt <- lm(fear~ treatment + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,partyid_close_cat=="Unaligned"))




## means

mn_like_trust <- mean(mechdat_pr$like_trust_nana[mechdat_pr$treatment_binary==0& mechdat_pr$partyid_close_cat=="Unaligned"])

mn_like <- mean(mechdat_pr$like_nana[mechdat_pr$treatment_binary==0& mechdat_pr$partyid_close_cat=="Unaligned"])

mn_trust <- mean(mechdat_pr$trust_nana[mechdat_pr$treatment_binary==0& mechdat_pr$partyid_close_cat=="Unaligned"])

mn_locdev <- mean(mechdat_pr$agree_local_nana_rev[mechdat_pr$treatment_binary==0& mechdat_pr$partyid_close_cat=="Unaligned"])

mn_locdev_tr <- mean(mechdat_pr$agree_local_nana_rev[mechdat_pr$treatment_binary==1& mechdat_pr$partyid_close_cat=="Unaligned"])

mn_locdev_sd <- sd(mechdat_pr$agree_local_nana_rev[mechdat_pr$treatment_binary==0& mechdat_pr$partyid_close_cat=="Unaligned"])

mn_natdev <- mean(mechdat_pr$agree_national_nana_rev[mechdat_pr$treatment_binary==0& mechdat_pr$partyid_close_cat=="Unaligned"])



mn_earnana <- mean(mechdat_pr$ear_nana_rev[mechdat_pr$treatment_binary==0& mechdat_pr$partyid_close_cat=="Unaligned"])

mn_worknana <- mean(mechdat_pr$devt_nana_rev[mechdat_pr$treatment_binary==0& mechdat_pr$partyid_close_cat=="Unaligned"])


mn_pers <- mean(mechdat_pr$personal_nana_rev[mechdat_pr$treatment_binary==0& mechdat_pr$partyid_close_cat=="Unaligned"])


mn_fear <- mean(mechdat_pr$fear[mechdat_pr$treatment_binary==0& mechdat_pr$partyid_close_cat=="Unaligned"])

mn_community <- mean(master$disadv[ mechdat_pr$partyid_close_cat=="Unaligned"]==2, na.rm = T)

mn_personal <- mean(master$disadv[ mechdat_pr$partyid_close_cat=="Unaligned"]==1, na.rm = T)
  
```

```{r}


#| label: mech-mediation
#| results: asis 
#| message: false
#| echo: true
#| eval: true
#| warning: true
#| include: true



mechdat_pr <- master%>%
  dplyr::select(vote_int_2020_endorsed_voters, like_nana,trust_nana,agree_local_nana_rev,agree_national_nana_rev,ear_nana_rev,devt_nana_rev,personal_nana_rev, fear, treatment_binary,treatment,age, education, total_assets, npp_scale, electoral_area, party_cluster_collapse3,like_trust_nana,partyid_close_cat)%>%
  mutate(party_cluster_collapse3 = relevel(party_cluster_collapse3, "NPP"),
         age_cat = factor(ifelse(age >= 18 & age <=35, 1, ifelse(age >= 36 & age <= 55,2,3)))
         )


#dim(mechdat_pr)
mechdat_pr <- na.omit(mechdat_pr)
#dim(mechdat_pr)


mechdat_pr_opp <- filter(mechdat_pr,partyid_close_cat=="Unaligned")


set.seed(45755)

# personal qualities 
##like
md1_medlike <- lm(like_trust_nana~ treatment_binary + age + education + total_assets+npp_scale+ electoral_area, data=mechdat_pr_opp)

md1_outlike <- lm(vote_int_2020_endorsed_voters~ like_trust_nana+ treatment_binary + age + education + total_assets+npp_scale+ electoral_area, data=mechdat_pr_opp)


## mediation analysis 
med_out_like <- mediate(md1_medlike, md1_outlike, treat = "treatment_binary", mediator = "like_trust_nana", robustSE = FALSE)

med_out_liketab <- tidy(med_out_like,conf.int = TRUE)[1,]

# local public goods

md1_medloc <- lm(agree_local_nana_rev~ treatment_binary + age + education + total_assets+npp_scale+ electoral_area, data=mechdat_pr_opp)

md1_outloc <- lm(vote_int_2020_endorsed_voters~ agree_local_nana_rev+ treatment_binary + age + education + total_assets+npp_scale+ electoral_area , data=mechdat_pr_opp)


## mediation analysis 
med_out_loc <- mediate(md1_medloc, md1_outloc, treat = "treatment_binary", mediator = "agree_local_nana_rev", robustSE = FALSE)

med_out_loctab <- tidy(med_out_loc,conf.int = TRUE)[1,]


## national policy
md1_mednatpol <- lm(agree_national_nana_rev~ treatment_binary + age + education + total_assets+npp_scale+ electoral_area, data=mechdat_pr_opp)

md1_outnatpol <- lm(vote_int_2020_endorsed_voters~ agree_national_nana_rev+ treatment_binary + age + education + total_assets+npp_scale+ electoral_area, data=mechdat_pr_opp)


## mediation analysis 
med_out_natpol <- mediate(md1_mednatpol, md1_outnatpol, treat = "treatment_binary", mediator = "agree_national_nana_rev", robustSE = FALSE)

med_out_natpoltab <- tidy(med_out_natpol,conf.int = TRUE)[1,]



## chief relations
#ear of president

md1_medear <- lm(ear_nana_rev~ treatment_binary + age + education + total_assets+npp_scale+ electoral_area, data=mechdat_pr_opp)

md1_outear <- lm(vote_int_2020_endorsed_voters~ ear_nana_rev+ treatment_binary + age + education + total_assets+npp_scale+ electoral_area , data=mechdat_pr_opp)

## mediation analysis 
med_out_ear <- mediate(md1_medear, md1_outear, treat = "treatment_binary", mediator = "ear_nana_rev", robustSE =FALSE)

med_out_eartab <- tidy(med_out_ear ,conf.int = TRUE)[1,]



#work well with president

md1_medwdevtch <- lm(devt_nana_rev~ treatment_binary + age + education + total_assets+npp_scale+ electoral_area, data=mechdat_pr_opp)

md1_outwdevtch <- lm(vote_int_2020_endorsed_voters~ devt_nana_rev+ treatment_binary + age + education + total_assets+npp_scale+ electoral_area, data=mechdat_pr_opp)

## mediation analysis 
med_out_wdevtch <- mediate(md1_medwdevtch, md1_outwdevtch, treat = "treatment_binary", mediator = "devt_nana_rev", robustSE = FALSE)

med_out_wdevtchtab <- tidy(med_out_wdevtch ,conf.int = TRUE)[1,]


## put chief in a position to provide personal benefit

md1_medper <- lm(personal_nana_rev~ treatment_binary + age + education + total_assets+npp_scale+ electoral_area, data=mechdat_pr_opp)

md1_outper <- lm(vote_int_2020_endorsed_voters~ personal_nana_rev+ treatment_binary + age + education + total_assets+npp_scale+ electoral_area, data=mechdat_pr_opp)

## mediation analysis 
med_out_per <- mediate(md1_medper, md1_outper, treat = "treatment_binary", mediator = "personal_nana_rev", robustSE = FALSE)

med_out_pertab <- tidy(med_out_per ,conf.int = TRUE)[1,]


# fear 

md1_medfear <- lm(fear~ treatment_binary + age + education + total_assets+npp_scale+ electoral_area, data=mechdat_pr_opp)

md1_outfear <- lm(vote_int_2020_endorsed_voters~ fear+ treatment_binary + age + education + total_assets+npp_scale+ electoral_area, data=mechdat_pr_opp)

## mediation analysis 
med_out_fear <- mediate(md1_medfear, md1_outfear, treat = "treatment_binary", mediator = "fear", robustSE = FALSE)

med_out_feartab <- tidy(med_out_fear ,conf.int = TRUE)[1,]
```

```{r}

#| label: mech-mediation-tab
#| results: asis 
#| message: false
#| echo: true
#| eval: true
#| warning: true
#| include: true

## Replication: Table 4

mechtab_main%>%
  dplyr::mutate(med_est= round(c(med_out_liketab$estimate, med_out_loctab$estimate,med_out_natpoltab$estimate, med_out_eartab$estimate,med_out_wdevtchtab$estimate, med_out_pertab$estimate, med_out_feartab$estimate),3),med_se= round(c(med_out_liketab$std.error, med_out_loctab$std.error,med_out_natpoltab$std.error, med_out_eartab$std.error,med_out_wdevtchtab$std.error, med_out_pertab$std.error, med_out_feartab$std.error),3), prop_med= round(c(med_out_like$n.avg, med_out_loc$n.avg,med_out_natpol$n.avg, med_out_ear$n.avg,med_out_wdevtch$n.avg, med_out_per$n.avg, med_out_fear$n.avg)*100,2),prop_med_p= round(c(med_out_like$n.avg.p, med_out_loc$n.avg.p,med_out_natpol$n.avg.p, med_out_ear$n.avg.p,med_out_wdevtch$n.avg.p, med_out_per$n.avg.p, med_out_fear$n.avg.p),3))%>%
  kbl(caption = "Average ITT effects of chiefly endorsement on intermediate outcomes",digits = 3,col.names = c("Variable","Mean", "SE", "Mean","SE", "ITT effect","SE", "P-value","ACME","SE","% of total effect mediated","P-value"),booktabs = T,label = "itt_mediate") %>%
  add_header_above(c(" " = 1, "Control group\n N=178" = 2, "Treatment group\n N=334" = 2, "Estimated ITT"=3, "Mediation"=4))%>%
  kable_classic(full_width = F, html_font = "Cambria",font_size=8)%>%
  column_spec(1, width = "18em")%>%
  pack_rows("Personal quality", 1,1)%>%
  pack_rows("Expected performance", 2,3)%>%
  pack_rows("Chief-politician relationship", 4,5)%>%
  pack_rows("Voter's private gain", 6,6)%>%
  pack_rows("Fear", 7,7)
```

```{=tex}
\appendix
\setcounter{page}{1}
\numberwithin{figure}{section}
\numberwithin{table}{section}
```
# Appendix {#appendixes .unnumbered}

# Balance statistics

```{r}

#| label: balance-tab
#| results: hide 
#| message: FALSE
#| echo: true
#| eval: true
#| warning: true



resp_char <- master%>%dplyr::select(age, female,primaryeduc_or_less, agric_worker,pettytrader,artisans, close_party, close_to_ndc, close_to_npp, turnout_2016, asante:ewe_anglo, correct_chiefname,dis_to_palace_KM_impt, treatment, treatment_binary)%>%
  mutate(tr_full_cont= ifelse(treatment=="placebo",0,ifelse(treatment=="full", 1, NA)),tr_endorse_cont =  ifelse(treatment=="placebo",0,ifelse(treatment=="onlyendorse", 1, NA)))

pvalue_fulsamp <- with(resp_char, c(t.test(age~treatment_binary)$p.value,
  t.test(female~treatment_binary)$p.value,
  t.test(primaryeduc_or_less~treatment_binary)$p.value,
  t.test(agric_worker~treatment_binary)$p.value,
  t.test(pettytrader~treatment_binary)$p.value,
  t.test(artisans~treatment_binary)$p.value,
  t.test(close_party~treatment_binary)$p.value,
  t.test(close_to_ndc~treatment_binary)$p.value,
  t.test(close_to_npp~treatment_binary)$p.value,
  t.test(turnout_2016~treatment_binary)$p.value,
  t.test(asante~treatment_binary)$p.value,
  t.test(bono~treatment_binary)$p.value,
  t.test(dagati~treatment_binary)$p.value,
  t.test(ahafo~treatment_binary)$p.value,
  t.test(ewe_anglo~treatment_binary)$p.value,
  t.test(correct_chiefname~treatment_binary)$p.value,
    t.test(dis_to_palace_KM_impt~treatment_binary)$p.value))


pvalue_endc <- with(resp_char, c(t.test(age~tr_endorse_cont)$p.value,
  t.test(female~tr_endorse_cont)$p.value,
  t.test(primaryeduc_or_less~tr_endorse_cont)$p.value,
  t.test(agric_worker~tr_endorse_cont)$p.value,
  t.test(pettytrader~tr_endorse_cont)$p.value,
  t.test(artisans~tr_endorse_cont)$p.value,
  t.test(close_party~tr_endorse_cont)$p.value,
  t.test(close_to_ndc~tr_endorse_cont)$p.value,
  t.test(close_to_npp~tr_endorse_cont)$p.value,
  t.test(turnout_2016~tr_endorse_cont)$p.value,
  t.test(asante~tr_endorse_cont)$p.value,
  t.test(bono~tr_endorse_cont)$p.value,
  t.test(dagati~tr_endorse_cont)$p.value,
  t.test(ahafo~tr_endorse_cont)$p.value,
  t.test(ewe_anglo~tr_endorse_cont)$p.value,
  t.test(correct_chiefname~tr_endorse_cont)$p.value,
    t.test(dis_to_palace_KM_impt~tr_endorse_cont)$p.value))

pvalue_fc <- with(resp_char, c(t.test(age~tr_full_cont)$p.value,
  t.test(female~tr_full_cont)$p.value,
  t.test(primaryeduc_or_less~tr_full_cont)$p.value,
  t.test(agric_worker~tr_full_cont)$p.value,
  t.test(pettytrader~tr_full_cont)$p.value,
  t.test(artisans~tr_full_cont)$p.value,
  t.test(close_party~tr_full_cont)$p.value,
  t.test(close_to_ndc~tr_full_cont)$p.value,
  t.test(close_to_npp~tr_full_cont)$p.value,
  t.test(turnout_2016~tr_full_cont)$p.value,
  t.test(asante~tr_full_cont)$p.value,
  t.test(bono~tr_full_cont)$p.value,
  t.test(dagati~tr_full_cont)$p.value,
  t.test(ahafo~tr_full_cont)$p.value,
  t.test(ewe_anglo~tr_full_cont)$p.value,
  t.test(correct_chiefname~tr_full_cont)$p.value,
    t.test(dis_to_palace_KM_impt~tr_full_cont)$p.value))

bal_tab <- tibble(var= rep(c("Age", "Gender (Female=1)", "Education (Primary or less =1)", "Employment (Farming=1)","Employment (Petty trading=1)", "Employment (Artisan=1)", "Close to a political party", "Close to the NDC", "Close to the NPP", "2016 Turnout", "Asante", "Bono", "Dagati", "Ahafo", "Ewe Anglo", "Correctly name chief", "Distance to chief's palace (KMs)"),3),`P-value`= c(pvalue_fulsamp, pvalue_endc,pvalue_fc), `Balance statistic`=c(rep(c("Treatment (any) vs. ctrl.", "Endorse vs. ctrl.", "Endorse/rationale vs. ctrl."), each=length(pvalue_endc))),y=c(rep(c(1:length(pvalue_endc)),3)))
```

```{r}

#| label: bal-stat
#| results: hide 
#| message: FALSE
#| echo: true
#| eval: true
#| warning: true
#| fig.cap: 'Balance statistics'
#| fig.align: 'center'
#| fig.height: 9
#| fig.width: 15


varlab <-c("Age", "Gender (Female=1)", "Education (Primary or less =1)", "Employment (Farming=1)","Employment (Petty trading=1)", "Employment (Artisan=1)", "Close to a political party", "Close to the NDC", "Close to the NPP", "2016 Turnout", "Asante", "Bono", "Dagati", "Ahafo", "Ewe Anglo", "Correctly name chief", "Distance to chief's palace (KMs)")


ggplot(bal_tab,mapping = aes(x=`P-value`,y=y))+
  geom_point()+
  geom_vline(xintercept =0.05,size=1.5,linetype=2,color="black")+
  scale_x_continuous(breaks=c(0.05, 0.5),limits = c(0,1))+
  scale_y_continuous(breaks=1:17,label=varlab,limits = c(0.5,17.5))+
  labs(y="",title="")+
  theme_tufte()+
  plottheme +
  facet_wrap(~`Balance statistic`)

```

```{=tex}
\FloatBarrier
\newpage
```
# Manipulation check

```{r}

#| label: mani-check
#| results: hide 
#| message: FALSE
#| echo: true
#| eval: true
#| warning: true

tab_manck <-master%>%
  dplyr::group_by(treatment)%>%
  dplyr::summarise(Yes=mean(classify_code,na.rm = T))


tab_manck %>%
  dplyr::mutate(varlab= c("Placebo", "Endorsement (A)", "Endorsement (A) + rationale (B)"))%>%
  dplyr::select(varlab, Yes)%>%
  kbl(caption = "Manipulation check", digits = 3,col.names = c("Treatment condition", "Proportion"),booktabs = T,label = "manicheck", longtable = T) %>%
  kable_classic(full_width = F)%>% footnote(general= "Proportion of respondents saying 'Yes' to the question: 'Thinking back to the audio I just played to you, do you think it was an endorsement for Nana Akufo-Addo' ", footnote_as_chunk = T, threeparttable = T)
  
```

\newpage

# Main results tables

\label{maintables}

\newpage

## Effect of chiefly endorsement on vote choice

```{r}
#| label: main-tab1
#| results: hide 



m1 <-h2_intention_full_no_controls
m2 <- h2_intention_full_controls
m3 <- h2_1_2
m4 <- h2_1_2_controls

m5 <- h2_1_2b
m6 <- h2_1_2_controlsb



stargazer::stargazer(m1,m2,m3,m4
   ,m5,m6,
  #font.size="scriptsize",
  type = "latex",
  title = "Average ITT effect of chiefly endorsement on vote choice (Pre-election)",
  #column.labels = c("Model A", "Model B", "Model C", "Model D"),
  dep.var.labels = c("Chose endorsed candidate"),
  covariate.labels = c("Any endorsement message", "Age", "Education", "Total assets", "Closeness to incumbent party (NPP)", "Endorsement Only", "Endorsement and rationale", "Placebo video", "Endorsement and rationale"),
  add.lines = list(c("EA fixed effects", rep(c("No","Yes"),3))),
  multicolumn = T,
  omit = "electoral_area",
  keep.stat = c("n","rsq"),
  notes.align = "l",
  style = "apsr",
  label = "mainvote",
  header=F
  )

```

\FloatBarrier

```{r}
#| label: main-tab2
#| results: hide 
#| message: FALSE
#| echo: true
#| eval: true
#| warning: true



m7 <- h2_actual_full_no_controls
m8 <- h2_actual_full_controls
m9 <- h2_1_2_actual
m10 <- h2_1_2_actual_controls
m11 <- h2_1_2_actualb
m12 <- h2_1_2_actual_controlsb



stargazer::stargazer(m7,m8,m9,m10,m11,m12,
  #font.size="scriptsize",
  type = "latex",
  title = "Average ITT effect of chiefly endorsement on vote choice (post-election survey)",
  #column.labels = c("Model A", "Model B", "Model C", "Model D"),
  dep.var.labels = c("Voted endorsed candidate"),
  covariate.labels = c("Any endorsement message", "Age", "Education", "Total assets", "Closeness to incumbent party (NPP)", "Endorsement Only", "Endorsement and rationale", "Placebo video", "Endorsement and rationale"),
  add.lines = list(c("EA fixed effects", rep(c("No","Yes"),3))),
  multicolumn = T,
  omit = "electoral_area",
  keep.stat = c("n","rsq"),
  notes.align = "l",
  style = "apsr",
  label = "mainpost",
  header=F
  )
```

## Do results hold if we exclude respondents who failed the manipulation check?

```{r, message=FALSE,echo=FALSE, eval=TRUE, warning=FALSE}

#| label: main-disag-post
#| results: hide 
#| message: FALSE
#| echo: true
#| eval: true
#| warning: true


trydat_pr_mani <- master%>%
  dplyr::select(turnout_int_2020,vote_int_2020_endorsed_voters,treatment_binary,treatment,age, education, total_assets, npp_scale, electoral_area, party_cluster_collapse3,vote_nana_lk,dis_to_palace_KM_impt,constituency,classify_code)%>%
  dplyr::mutate(party_cluster_collapse3 = relevel(party_cluster_collapse3, "NPP"),
         age_cat = factor(ifelse(age >= 18 & age <=35, 1, ifelse(age >= 36 & age <= 55,2,3))),
         dist_cat= factor(ifelse(dis_to_palace_KM_impt <=5,2, ifelse(dis_to_palace_KM_impt >5 &dis_to_palace_KM_impt <=10, 1, 0))), failmanitest= ifelse(treatment_binary==1&classify_code==1|treatment_binary==0&classify_code==0,0,1)
         )

trydat_post_mani <- master%>%
  dplyr::select(turnout_actual_binary, vote_2020_endorsed,treatment_binary,treatment,age, education, total_assets, npp_scale, electoral_area, party_cluster_collapse3,dis_to_palace_KM_impt,constituency,classify_code)%>%
  mutate(party_cluster_collapse3 = relevel(party_cluster_collapse3, "NPP"),
         age_cat = factor(ifelse(age >= 18 & age <=35, 1, ifelse(age >= 36 & age <= 55,2,3))),
         dist_cat= factor(ifelse(dis_to_palace_KM_impt <=5,2, ifelse(dis_to_palace_KM_impt >5 &dis_to_palace_KM_impt <=10, 1, 0 ))), failmanitest= ifelse(treatment_binary==1&classify_code==1|treatment_binary==0&classify_code==0,0,1)
         )


#dim(trydat_pr)
trydat_pr_mani <- na.omit(trydat_pr_mani)
#dim(trydat_pr)

#dim(trydat_post)
trydat_post_mani <- na.omit(trydat_post_mani)
#dim(trydat_post)




# vote choice
h2_intention_full_no_controls_mani <- lm(vote_int_2020_endorsed_voters ~ treatment_binary, data=dplyr::filter(trydat_pr_mani, failmanitest==0))

h2_intention_full_controls_mani <- lm(vote_int_2020_endorsed_voters ~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=dplyr::filter(trydat_pr_mani, failmanitest==0))


h2_actual_full_no_controls_mani <- lm(vote_2020_endorsed ~ treatment_binary, data=dplyr::filter(trydat_post_mani, failmanitest==0))

h2_actual_full_controls_mani <- lm(vote_2020_endorsed ~ treatment_binary + age + education + total_assets + npp_scale + as.factor(electoral_area), data=dplyr::filter(trydat_post_mani, failmanitest==0))

h2_1_2_mani <- lm(vote_int_2020_endorsed_voters ~ treatment, data=dplyr::filter(trydat_pr_mani,failmanitest==0))

h2_1_2_controls_mani <- 
lm(vote_int_2020_endorsed_voters ~ treatment + age + education + total_assets + npp_scale + electoral_area, data=dplyr::filter(trydat_pr_mani, failmanitest==0))

h2_1_2_actual_mani <- lm(vote_2020_endorsed ~ treatment, data=dplyr::filter(trydat_post_mani, failmanitest==0))

h2_1_2_actual_controls_mani <- lm(vote_2020_endorsed ~ treatment + age + education + total_assets + npp_scale + as.factor(electoral_area), data=dplyr::filter(trydat_post_mani, failmanitest==0))



itt_estimates_mani <- tibble(rowname= c("itt_pre_vote", "itt_post_vote"),group1=as.character(2), 
                        mean= c(summary(h2_intention_full_controls_mani)$coefficients[2,1], summary(h2_actual_full_controls_mani)$coefficients[2,1]),  
se=c(summary(h2_intention_full_controls_mani)$coefficients[2,2], summary(h2_actual_full_controls_mani)$coefficients[2,2]))



## subset data to only those who did not fail manipulation test for summary stats

temp_pr <- dplyr::filter(trydat_pr_mani, failmanitest==0)

main_outsum_pr_mani <-temp_pr%>%
  dplyr::select(vote_int_2020_endorsed_voters)%>%
  psych::describeBy(group = temp_pr$treatment_binary,mat = TRUE)%>%
  as_tibble(rownames="rowname")%>%
  dplyr::select(rowname,n,group1,mean,se)

temp_post <- dplyr::filter(trydat_post_mani, failmanitest==0)

main_outsum_post_mani <- temp_post%>%
  dplyr::select(vote_2020_endorsed)%>%
  psych::describeBy(group = temp_post$treatment_binary,mat = TRUE)%>%
  as_tibble(rownames="rowname")%>%
  dplyr::select(rowname,n,group1,mean,se)


mainrestab_mani <- dplyr::bind_rows(main_outsum_pr_mani,main_outsum_post_mani,itt_estimates_mani)

mainrestab_mani <- mutate(mainrestab_mani, y_points=ifelse(group1=="0"|group1=="2", 1, 2),estimate_type=ifelse(group1=="0"|group1=="1", "Group means", "ITT"),  Wave=factor( c(rep("Pre-election",2), rep("Post-election",2), "Pre-election", "Post-election"), levels = c("Pre-election", "Post-election"),ordered = TRUE), type=c("Vote", "Vote","Vote", "Vote", "Vote", "Vote"))

```

\FloatBarrier

```{r}


#| label: main-vote-exmanip
#| results: hide 
#| message: FALSE
#| echo: true
#| eval: true
#| warning: true
#| fig.cap: 'Average intention-to-treat effect of chiefly endorsement on vote choice restricting sample to only those who passed manipulation check'
#| fig.align: 'center'
#| fig.height: 9
#| fig.width: 11




p3 <- ggplot(filter(mainrestab_mani, type=="Vote"&estimate_type=="Group means"),mapping = aes(x=mean, y=y_points))+
  geom_point(size=5)+
  geom_errorbar(mapping=aes(y=y_points, xmin=mean -1.96*se, xmax=mean+1.96*se),size=1,width=.01)+
  scale_y_continuous(breaks=c(1, 2),labels = c( "Control", "Treatment"),limits = c(0.5,2.2))+
  #scale_x_continuous(limits = c(-0.05,1))+
  labs(x ="Mean vote for endorsed", y="Treatment condition", title= "Panel A: treatment condition means")+
  theme_tufte()+
  plottheme +
  facet_wrap(~Wave,ncol = 2)



p4 <- ggplot(filter(mainrestab_mani, type=="Vote"&estimate_type=="ITT"),mapping = aes(x=mean, y=y_points))+
  geom_point(size=5)+
  geom_errorbar(mapping=aes(y=y_points, xmin=mean -1.96*se, xmax=mean+1.96*se),size=1,width=.01)+
  scale_y_continuous(breaks=c(1),labels = c( "Treatment"),limits = c(0.5,1.5))+
  geom_vline(xintercept =0,size=0.8,linetype=2,color="black")+
  #scale_x_continuous(limits = c(-0.05,1))+
  labs(x ="Change in vote for endorsed", y="Average ITT effect", title = "Panel B: effect of chiefly endorsement")+
  theme_tufte()+
   plottheme +
  facet_wrap(~Wave,ncol = 2)+theme(strip.text.x = element_blank(),axis.text.y =element_text(colour = "white"))


gt2_mani <- arrangeGrob(p3, p4, ncol = 1)
as_ggplot(gt2_mani)

```

\newpage

# Heterogeneous effects

\label{hetresults}

## Partisanship

```{r}

#| label: het-part-main
#| results: hide 
#| message: FALSE
#| echo: true
#| eval: true
#| warning: true
#| include: true


stargazer::stargazer(h2part_rb,h2part_c_rb, h2actual_rb,h2actual_c_rb,
  #font.size="footnotesize",
  type = "latex",
  title = "ITT effect of chiefly endorsement on vote choice by partisanship",
  #column.labels = c("Model A", "Model B", "Model C", "Model D"),
  dep.var.caption  = "Voted for endorsed",
  dep.var.labels = c("Pre-election","Post-election"),
  covariate.labels = c("Treatment", "Close to NDC", "Close to no party", "Treatment x Close to NDC", "Treatment x Close to no party"),
  add.lines = list(c("EA fixed effects", rep(c("No","Yes"),2)),c("Controls", rep(c("No","Yes"),2))),
  multicolumn = T,
  omit = c("age", "education","total_assets", "electoral_area"),
  keep.stat = c("n","rsq"),
  notes.align = "l",
  style = "apsr",
  label="het_party_rb1",
  header=F
  )
```

## Alternative specification of partisanship

```{r}
#| label: alternative-partisan-coding


dat_pr_rb <- master%>%
  dplyr::select(turnout_int_2020,vote_int_2020_endorsed_voters,treatment_binary,treatment,age, education, total_assets, npp_scale, electoral_area,vote_nana_lk,dis_to_palace_KM_impt,constituency,partyid_close_cat,partyid_cat_hist,chief_performance_rate)%>%
  dplyr::mutate(partyid_close_cat = relevel(partyid_close_cat, "NPP"),partyid_cat_hist = relevel(partyid_cat_hist, "NPP"),
         age_cat = factor(ifelse(age >= 18 & age <=35, 1, ifelse(age >= 36 & age <= 55,2,3))),
         dist_cat= factor(ifelse(dis_to_palace_KM_impt <=5,2, ifelse(dis_to_palace_KM_impt >5 &dis_to_palace_KM_impt <=10, 1, 0))),
         npp_scale_cat = relevel(factor(ifelse(is.na(npp_scale), NA, ifelse(npp_scale==0|npp_scale==1, "NDC", ifelse(npp_scale==6|npp_scale==7, "NPP", "Moderate")))),"NPP"),
         app_chief =ifelse(is.na(chief_performance_rate), NA, ifelse(chief_performance_rate>3,1,0))
         )
         
dat_post_rb <- master%>%
  dplyr::select(turnout_actual_binary, vote_2020_endorsed,treatment_binary,treatment,age, education, total_assets, npp_scale, electoral_area,dis_to_palace_KM_impt,constituency,partyid_close_cat,partyid_cat_hist,chief_performance_rate)%>%
  mutate(partyid_close_cat = relevel(partyid_close_cat, "NPP"),partyid_cat_hist = relevel(partyid_cat_hist, "NPP"),
         age_cat = factor(ifelse(age >= 18 & age <=35, 1, ifelse(age >= 36 & age <= 55,2,3))),
         dist_cat= factor(ifelse(dis_to_palace_KM_impt <=5,2, ifelse(dis_to_palace_KM_impt >5 &dis_to_palace_KM_impt <=10, 1, 0 ))),
         npp_scale_cat = relevel(factor(ifelse(is.na(npp_scale), NA, ifelse(npp_scale==0|npp_scale==1, "NDC", ifelse(npp_scale==6|npp_scale==7, "NPP", "Moderate")))), "NPP"),
         app_chief =ifelse(is.na(chief_performance_rate), NA, ifelse(chief_performance_rate>3,1,0))
         )


##1. partisanship is coded here to vote choices in the last two elections

h2part_rb2 <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*partyid_cat_hist, data=dat_pr_rb)

h2part_c_rb2 <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*partyid_cat_hist + age + education + total_assets + electoral_area, data=dat_pr_rb)

h2part_c_m_rb2 <- margins::margins(h2part_c_rb2,data=data.frame(dat_pr_rb), at = list("partyid_cat_hist" =c("NPP","NDC", "Swing/minor")))


sumtab_rb2 <- summary(h2part_c_m_rb2)[summary(h2part_c_m_rb2)$factor=="treatment_binary", c("partyid_cat_hist","AME","SE")]



h2actual_rb2 <- lm(vote_2020_endorsed ~ treatment_binary*partyid_cat_hist, data=dat_post_rb)

h2actual_c_rb2 <- lm(vote_2020_endorsed ~ treatment_binary*partyid_cat_hist + age + education + total_assets+ electoral_area, data=dat_post_rb)


h2actual_c_m_rb2 <- margins::margins(h2actual_c_rb2,data=data.frame(dat_post_rb), at = list("partyid_cat_hist" =c("NPP","NDC", "Swing/minor")))


sumtab1_rb2 <- summary(h2actual_c_m_rb2)[summary(h2actual_c_m_rb2)$factor=="treatment_binary", c("partyid_cat_hist","AME","SE")]



##2. partisanship coded on the npp scale (NPP=6/7, NDC= 0/1, Moderate 2-5)

h2part_rb3 <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*npp_scale_cat, data=dat_pr_rb)

h2part_c_rb3 <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*npp_scale_cat + age + education + total_assets + electoral_area, data=dat_pr_rb)

h2part_c_m_rb3 <- margins::margins(h2part_c_rb3,data=data.frame(dat_pr_rb), at = list("npp_scale_cat" =c("NPP","NDC", "Moderate")))


sumtab_rb3 <- summary(h2part_c_m_rb3)[summary(h2part_c_m_rb3)$factor=="treatment_binary", c("npp_scale_cat","AME","SE")]



h2actual_rb3 <- lm(vote_2020_endorsed ~ treatment_binary*npp_scale_cat, data=dat_post_rb)

h2actual_c_rb3 <- lm(vote_2020_endorsed ~ treatment_binary*npp_scale_cat + age + education + total_assets+ electoral_area, data=dat_post_rb)


h2actual_c_m_rb3 <- margins::margins(h2actual_c_rb3,data=data.frame(dat_post_rb), at = list("npp_scale_cat" =c("NPP","NDC", "Moderate")))


sumtab1_rb3 <- summary(h2actual_c_m_rb3)[summary(h2actual_c_m_rb3)$factor=="treatment_binary", c("npp_scale_cat","AME","SE")]

```

```{r}
#| label: alter-patisan-tab1

## Table F.2 

stargazer::stargazer(h2part_rb3,h2part_c_rb3, h2actual_rb3,h2actual_c_rb3,
  #font.size="footnotesize",
  type = "latex",
  title = "ITT effect of chiefly endorsement on vote choice by partisanship (closeness to NPP)",
  #column.labels = c("Model A", "Model B", "Model C", "Model D"),
  dep.var.caption  = "Voted for endorsed",
  dep.var.labels = c("Pre-election","Post-election"),
  covariate.labels = c("Treatment", "Moderate [2-5]", "NDC [0-1]", "Treatment x Moderate [2-5]", "Treatment x NDC [0-1]"),
  add.lines = list(c("EA fixed effects", rep(c("No","Yes"),2)),c("Controls", rep(c("No","Yes"),2))),
  multicolumn = T,
  omit = c("age", "education","total_assets", "electoral_area"),
  keep.stat = c("n","rsq"),
  notes.align = "l",
  style = "apsr",
  label="het_party_rb3",
  header=F
  )
```

```{r}

#| label: mainparty-rb3
#| results: asis
#| fig.align:center
#| fig.height: 6
#| fig.width: 10
#| fig.cap: Robust 1: Average Marginal Effect of Chiefly Endorsement on Vote Choice by Partisanship"


## Figure F.1

tab_party_het_rb3 = bind_rows(sumtab_rb3,sumtab1_rb3)%>%
  dplyr::mutate(Period= factor(c("Pre-election", "Pre-election","Pre-election", "Post-election", "Post-election","Post-election"), levels = c("Pre-election", "Post-election"), ordered = TRUE),point=c(0.9,1.9,2.9,1.1,2.1,3.1))

ggplot(tab_party_het_rb3,mapping = aes(x=point, y=AME, shape=Period))+
  geom_point(size=4)+
  geom_errorbar(mapping=aes(x=point, ymin=AME -1.96*SE, ymax=AME+1.96*SE),size=1,width=.01)+
  scale_x_continuous(breaks=c(1,2,3),labels = c("NPP (6-7)", "NDC (0-1)", "Moderate (2-5)"),limits = c(0.5,3.5))+
  scale_y_continuous(limits = c(-0.15,0.25))+
  geom_hline(yintercept = 0,linetype=2, color="black")+
  geom_vline(xintercept = c(1.5,2.5),linetype=2, color="grey",size=1.3)+
  labs(x ="Partisanship (closeness to NPP)", y="Average marginal effect of chiefly endorsement")+
  theme_tufte()+
  plottheme
```

```{r}

#| label: mainparty-tab2
#| results: asis


## Table F.3
stargazer::stargazer(h2part_rb2,h2part_c_rb2, h2actual_rb2,h2actual_c_rb2,
  #font.size="footnotesize",
  type = "latex",
  title = "ITT effect of chiefly endorsement on vote choice by partisanship (voting history)",
  #column.labels = c("Model A", "Model B", "Model C", "Model D"),
  dep.var.caption  = "Voted for endorsed",
  dep.var.labels = c("Pre-election","Post-election"),
  covariate.labels = c("Treatment", "NDC partisan", "Swing voter", "Treatment x NDC partisan", "Treatment x Swing voter"),
  add.lines = list(c("EA fixed effects", rep(c("No","Yes"),2)),c("Controls", rep(c("No","Yes"),2))),
  multicolumn = T,
  omit = c("age", "education","total_assets", "electoral_area"),
  keep.stat = c("n","rsq"),
  notes.align = "l",
  style = "apsr",
  label="het_party_rb2",
  header=F
  )
```

\FloatBarrier

```{r}
#| label: mainparty-rb2
#| results: asis
#| fig.align: center
#| fig.height: 6
#| fig.width: 10
#| fig.cap: 'Robust 1 Average Marginal Effect of Chiefly Endorsement on Vote Choice by Partisanship'



tab_party_het_rb2 = bind_rows(sumtab_rb2,sumtab1_rb2)%>%
  dplyr::mutate(Period= factor(c("Pre-election", "Pre-election","Pre-election", "Post-election", "Post-election","Post-election"), levels = c("Pre-election", "Post-election"), ordered = TRUE),point=c(0.9,1.9,2.9,1.1,2.1,3.1))

ggplot(tab_party_het_rb2,mapping = aes(x=point, y=AME, shape=Period))+
  geom_point(size=4)+
  geom_errorbar(mapping=aes(x=point, ymin=AME -1.96*SE, ymax=AME+1.96*SE),size=1,width=.01)+
  scale_x_continuous(breaks=c(1,2,3),labels = c("NPP", "NDC", "Swing/minor"),limits = c(0.5,3.5))+
  scale_y_continuous(limits = c(-0.15,0.45))+
  geom_hline(yintercept = 0,linetype=2, color="black")+
  geom_vline(xintercept = c(1.5,2.5),linetype=2, color="grey",size=1.3)+
  labs(x ="Party candidate in 2012 and 2016 presidential elections", y="Average marginal effect of chiefly endorsement")+
  theme_tufte()+
  plottheme
```

## Effect of cheifly endorsement by evaluation of chief's past performance

```{r}
#| label: main-chief
#| results: asis
#| fig.align: center
#| fig.height: 6
#| fig.width: 10
#| fig.cap: 'Average marginal effect of chiefly endorsement on vote choice by approval of chief'



tab_chief_het = bind_rows(sumtab_chap,sumtab1_chap1)%>%
  dplyr::mutate(Period= c("Pre-election", "Pre-election", "Post-election", "Post-election"),point=c(0.9,1.9,1.1,2.1))

ggplot(tab_chief_het,mapping = aes(x=point, y=AME, shape=Period))+
  geom_point(size=4)+
  geom_errorbar(mapping=aes(x=point, ymin=AME -1.96*SE, ymax=AME+1.96*SE),size=1,width=.01)+
  scale_x_continuous(breaks=c(1, 2),labels = c("Do not approve", "Approve"),limits = c(0.5,2.5))+
  scale_y_continuous(limits = c(-0.15,0.25))+
  geom_hline(yintercept = 0,linetype=2, color="grey")+
  geom_vline(xintercept = 1.5,linetype=2, color="grey",size=1.3)+
  labs(x ="Approval of chief's performance", y="Average marginal effect of chiefly endorsement")+
  theme_tufte()+
  plottheme
```

## Age

```{r}

#| label: main-age


h2part_age <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*age_cat, data=trydat_pr)

h2part_age_c <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*age_cat + education + total_assets + npp_scale + electoral_area, data=trydat_pr)


h2actual_age <- lm(vote_2020_endorsed ~ treatment_binary*age_cat, data=trydat_post)

h2actual_age_c <- lm(vote_2020_endorsed ~ treatment_binary*age_cat  + education + total_assets + npp_scale + as.factor(electoral_area), data=trydat_post)


##marginal effects

h2age_c_m <- margins::margins(h2part_age_c,data=data.frame(trydat_pr), at = list("age_cat" =factor(c(1:3))))

sumtab_age <- summary(h2age_c_m)[summary(h2age_c_m)$factor=="treatment_binary", c("age_cat","AME","SE")]

h2age_actual_c_m <- margins::margins(h2actual_age_c,data=data.frame(trydat_post), at = list("age_cat" =factor(c(1:3))))


sumtab1_age1 <- summary(h2age_actual_c_m)[summary(h2age_actual_c_m)$factor=="treatment_binary", c("age_cat","AME","SE")]


```

```{r}

#| label: main-age-tab
#| results: asis


## Table F.5 

stargazer::stargazer(h2part_age,h2part_age_c,h2actual_age,h2actual_age_c,
  #font.size="tiny",
  type = "latex",
  title = "ITT effect of chiefly endorsement on vote choice by age",
  #column.labels = c("Model A", "Model B", "Model C", "Model D"),
  dep.var.labels = c("Pre-election", "Post-election"),
  covariate.labels = c("Treatment (any)", "Age:36-55","Age: 56 and above", "Treatment (any) x Age:36-55", "Treatment (any) x Age: 56 and above"),
  add.lines = list(c("EA fixed effects", rep(c("No","Yes"),2)),c("Controls", rep(c("No","Yes"),2))),
  multicolumn = T,
  omit = c( "education","total_assets", "npp_scale", "electoral_area"),
  keep.stat = c("n","rsq"),
  notes.align = "l",
  style = "apsr",
  label = "het_age",
  header=F
  )
```

```{r}

#| label: main-age-plot
#| results: asis
#| fig.align:center
#| fig.height: 6
#| fig.width: 10
#| fig.cap: 'Average marginal effect of chiefly endorsement on vote choice by age'

## Figure F.4

tab_age_het = bind_rows(sumtab_age,sumtab1_age1)%>%
  dplyr::mutate(Period= c(rep("Pre-election",3), rep("Post-election",3)),point=c(0.4,0.9,1.4,1.6,1.1,0.6))

ggplot(tab_age_het,mapping = aes(x=point, y=AME, shape=Period, linetype=Period))+
  geom_point(size=4)+
  geom_line(size=1.2)+
  geom_errorbar(mapping=aes(x=point, ymin=AME -1.96*SE, ymax=AME+1.96*SE),size=1,width=.01)+
  scale_x_continuous(breaks=c(0.5, 1,1.5),labels = c("18-35", "36-55", "56 and above"),limits = c(0,2))+
  scale_y_continuous(limits = c(-0.15,0.25))+
  geom_hline(yintercept = 0,linetype=2, color="grey")+
  labs(x ="Respondents' age", y="Average marginal effect of chiefly endorsement")+
  theme_tufte()+
  plottheme

```

## Distance

```{r}

#| label: main-distance
#| results: asis


h2dist_c <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*dist_cat + age + education + total_assets + npp_scale + electoral_area, data=trydat_pr)


h2dist_actual_c <- lm(vote_2020_endorsed ~ treatment_binary*dist_cat + age + education + total_assets + npp_scale + electoral_area, data=trydat_post)


h2dist_c_m <- margins::margins(h2dist_c,data=data.frame(trydat_pr), at = list("dist_cat" =factor(c(0,1,2))))

sumtab_dist <- summary(h2dist_c_m)[summary(h2dist_c_m)$factor=="treatment_binary", c("dist_cat","AME","SE")]



h2dist_actual_c_m <- margins::margins(h2dist_actual_c,data=data.frame(trydat_post), at = list("dist_cat" =factor(c(0,1,2))))


sumtab1_dist1 <- summary(h2dist_actual_c_m)[summary(h2dist_actual_c_m)$factor=="treatment_binary", c("dist_cat","AME","SE")]
```

```{r}

#| label: main-dist-plot
#| results: asis
#| fig.align:center
#| fig.height: 8
#| fig.width: 16
#| fig.cap: 'Average marginal effect of chiefly endorsement on vote choice by distance'

## Figure F.4


tab_dist_het = dplyr::bind_rows(sumtab_dist,sumtab1_dist1)%>%
  dplyr::mutate(Period= c(rep("Pre-election",3), rep("Post-election",3)),point=c(1.4,0.9,0.4,1.6,1.1,0.6))

ggplot(tab_dist_het,mapping = aes(x=point, y=AME, shape=Period, linetype=Period))+
  geom_point(size=4)+
  geom_line(size=1.2)+
  geom_errorbar(mapping=aes(x=point, ymin=AME -1.96*SE, ymax=AME+1.96*SE),size=1,width=.01)+
  scale_x_continuous(breaks=c(0.5, 1,1.5),labels = c("Near (within 5 Km)", "Midrange (5 - 10 Km)", "Far (more than 10 Km)"),limits = c(0,2))+
  scale_y_continuous(limits = c(-0.15,0.25))+
  geom_hline(yintercept = 0,linetype=2, color="grey")+
  labs(x ="Distance to chief's palace", y="Average marginal effect of chiefly endorsement")+
  theme_tufte()+
  plottheme

```

## Does a particular traditional area drive the results?

```{r}
#| label: trad-robust
#| results: asis

trydat_pr <- master%>%
  dplyr::select(turnout_int_2020,vote_int_2020_endorsed_voters,treatment_binary,treatment,age, education, total_assets, npp_scale, electoral_area, party_cluster_collapse3,vote_nana_lk,dis_to_palace_KM_impt,constituency,female, trad_area.x, agric_worker,correct_chiefname,tribe,partyid_close_cat)%>%
  dplyr::mutate(party_cluster_collapse3 = relevel(party_cluster_collapse3, "NPP"),
         age_cat = factor(ifelse(age >= 18 & age <=35, 1, ifelse(age >= 36 & age <= 55,2,3))),
         dist_cat= factor(ifelse(dis_to_palace_KM_impt <=5,2, ifelse(dis_to_palace_KM_impt >5 &dis_to_palace_KM_impt <=10, 1, 0))),gender_cat= factor(ifelse(female==0, "Male", ifelse(female==1, "Female", NA)), levels = c("Male", "Female")), farmer= factor(ifelse(agric_worker==0, "Other profession", ifelse(agric_worker==1, "Farmer", NA)), levels = c("Other profession", "Farmer")),
        correctly_name_chief= factor(ifelse(correct_chiefname==0, "No", ifelse(correct_chiefname==1, "Yes", NA)), levels = c("No", "Yes")), majority_ethnic_bono = factor(ifelse(tribe==3, "Bono", ifelse(tribe!=3, "Minority group", NA)), levels = c("Bono", "Minority group")),
          majority_ethnic_bono_asante = factor(ifelse(tribe==3|tribe==1, "Bono/Asante", ifelse(!(tribe==3|tribe==1), "Minority group", NA)), levels = c("Bono/Asante", "Minority group")) )


trydat_post <- master%>%
  dplyr::select(turnout_actual_binary, vote_2020_endorsed,treatment_binary,treatment,age, education, total_assets, npp_scale, electoral_area, party_cluster_collapse3,dis_to_palace_KM_impt,constituency,female, trad_area.x, agric_worker,correct_chiefname,tribe,partyid_close_cat)%>%
  mutate(party_cluster_collapse3 = relevel(party_cluster_collapse3, "NPP"),
         age_cat = factor(ifelse(age >= 18 & age <=35, 1, ifelse(age >= 36 & age <= 55,2,3))),
         dist_cat= factor(ifelse(dis_to_palace_KM_impt <=5,2, ifelse(dis_to_palace_KM_impt >5 &dis_to_palace_KM_impt <=10, 1, 0 ))),
         gender_cat= factor(ifelse(female==0, "Male", ifelse(female==1, "Female", NA)), levels = c("Male", "Female")), farmer= factor(ifelse(agric_worker==0, "Other profession", ifelse(agric_worker==1, "Farmer", NA)), levels = c("Other profession", "Farmer")),
        correctly_name_chief= factor(ifelse(correct_chiefname==0, "No", ifelse(correct_chiefname==1, "Yes", NA)), levels = c("No", "Yes")), majority_ethnic_bono = factor(ifelse(tribe==3, "Bono", ifelse(tribe!=3, "Minority group", NA)), levels = c("Bono", "Minority group")),
          majority_ethnic_bono_asante = factor(ifelse(tribe==3|tribe==1, "Bono/Asante", ifelse(!(tribe==3|tribe==1), "Minority group", NA)), levels = c("Bono/Asante", "Minority group"))
         )


#dim(trydat_pr)
trydat_pr <- na.omit(trydat_pr)
#dim(trydat_pr)

#dim(trydat_post)
trydat_post <- na.omit(trydat_post)
#dim(trydat_post)



trydat_pr <- dplyr::mutate(trydat_pr, nisp=ifelse(party_cluster_collapse3=="NPP",0,1), trad_area= ifelse(constituency=="JAMAN_SOUTH", "Drobo", ifelse(constituency=="TECHIMAN_SOUTH", "Techiman", "Duayaw Nkwanta")))

trydat_post <- dplyr::mutate(trydat_post,trad_area= ifelse(constituency=="JAMAN_SOUTH", "Drobo", ifelse(constituency=="TECHIMAN_SOUTH", "Techiman", "Duayaw Nkwanta")))

h2tradarea_c <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*trad_area.x + age + education + total_assets + npp_scale, data=trydat_pr)


h2tradarea_actual_c <- lm(vote_2020_endorsed ~ treatment_binary*trad_area.x + age + education + total_assets + npp_scale, data=trydat_post)


h2tradarea_c_m <- margins::margins(h2tradarea_c,data=data.frame(trydat_pr), at = list("trad_area.x" =factor(c("Drobo","Duayaw_Nkwanta","Techiman"))))

sumtab_tradrea <- summary(h2tradarea_c_m)[summary(h2tradarea_c_m)$factor=="treatment_binary", c("trad_area.x","AME","SE")]



h2tradarea_actual_c_m <- margins::margins(h2tradarea_actual_c,data=data.frame(trydat_post), at = list("trad_area.x" =factor(c("Drobo","Duayaw_Nkwanta","Techiman"))))


sumtab1_tradrea1 <- summary(h2tradarea_actual_c_m)[summary(h2tradarea_actual_c_m)$factor=="treatment_binary", c("trad_area.x","AME","SE")]
```

```{r}

#| label: main-tradarea
#| results: asis
#| fig.align:center
#| fig.height: 8
#| fig.width: 16
#| fig.cap: 'Average marginal effect of chiefly endorsement on vote choice by traditional area'

## Figure F.7

tab_het_tradarea <- bind_rows(sumtab_tradrea,sumtab1_tradrea1)%>%
  dplyr::mutate(Period= c("Pre-election", "Pre-election","Pre-election",  "Post-election", "Post-election","Post-election"),point=c(0.9,1.9,2.9, 1.1,2.1,3.1))

ggplot(tab_het_tradarea,mapping = aes(x=point, y=AME, shape=Period))+
  geom_point(size=4)+
  geom_errorbar(mapping=aes(x=point, ymin=AME -1.96*SE, ymax=AME+1.96*SE),size=1,width=.01)+
  scale_x_continuous(breaks=c(1, 2,3),labels = c("Drobo", "Duayaw Nkwanta", "Techiman"),limits = c(0.5,3.5))+
  scale_y_continuous(limits = c(-0.15,0.25))+
  geom_hline(yintercept = 0,linetype=2, color="grey")+
  geom_vline(xintercept = c(1.5,2.5),linetype=2, color="grey",size=1.3)+
  labs(x ="Traditional area", y="Average marginal effect of chiefly endorsement")+
  theme_tufte()+
  plottheme
```

\FloatBarrier

```{r}

#| label: main-tradarea-het
#| results: asis

# estimates for the different traditional areas

## pre-election estimates by traditional area

prehetpart_trad <- vector(mode = "list")

trad_areas <- c("Drobo", "Techiman", "Duayaw Nkwanta")

for(trad in trad_areas ){
  
temp <- dplyr::filter(trydat_pr,grepl(trad,trad_area))

h2part_c_temp <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*partyid_close_cat + age + education + total_assets + electoral_area, data=temp)

h2part_c_m_temp <- margins::margins(h2part_c_temp,data=data.frame(temp), at = list("partyid_close_cat" =c("NPP","NDC", "Unaligned")))

sumtab <- summary(h2part_c_m_temp)[summary(h2part_c_m_temp)$factor=="treatment_binary", c("partyid_close_cat","AME","SE")]

prehetpart_trad[[trad]] <- sumtab
}


### post election estimates by traditional area

posthetpart_trad <- vector(mode = "list")

for(trad in trad_areas ){
temp <- dplyr::filter(trydat_post,grepl(trad,trad_area))

h2actual_c_temp <- lm(vote_2020_endorsed ~ treatment_binary*partyid_close_cat + age + education + total_assets+ electoral_area, data=temp)


h2actual_c_m_temp <- margins::margins(h2actual_c_temp,data=data.frame(temp), at = list("partyid_close_cat" =c("NPP","NDC", "Unaligned")))


sumtab1 <- summary(h2actual_c_m_temp)[summary(h2actual_c_m_temp)$factor=="treatment_binary", c("partyid_close_cat","AME","SE")]

posthetpart_trad[[trad]] <- sumtab1
}

#create dataset to combine estimates for plotting

hetpartisan_bytrad <- bind_rows(prehetpart_trad$Drobo,prehetpart_trad$Techiman,prehetpart_trad$`Duayaw Nkwanta`,posthetpart_trad$Drobo,posthetpart_trad$Techiman,posthetpart_trad$`Duayaw Nkwanta`)
                                

hetpartisan_bytrad <- mutate(hetpartisan_bytrad, Period= factor(c(rep("Pre-election",9),rep("Post-election",9)), levels = c("Pre-election", "Post-election"), ordered = TRUE), `Traditional area`= rep(c("Drobo", "Drobo","Drobo","Techiman","Techiman","Techiman","Duayaw Nkwanta","Duayaw Nkwanta","Duayaw Nkwanta"), 2),label=factor( ifelse(partyid_close_cat=="Unaligned","Unaligned",ifelse(partyid_close_cat=="NPP","Incumbent", "Opposition")), levels = c("Incumbent", "Opposition", "Unaligned"), ordered = TRUE),point= c(rep(c(0.9, 1.9,2.9),3),rep(c(1.1, 2.1,3.1),3)))
```

```{r}


#| label: main-tradarea-het-plot
#| results: asis
#| fig.align: center
#| fig.height: 8
#| fig.width: 15
#| fig.cap: 'Average marginal effect of chiefly endorsement on vote choice by partisanship and traditional area'

## Figure F.7



ggplot(hetpartisan_bytrad,mapping = aes(x=point, y=AME, shape=Period))+
  geom_point(size=4)+
  geom_errorbar(mapping=aes(x=point, ymin=AME -1.96*SE, ymax=AME+1.96*SE),size=1,width=.01)+
  scale_x_continuous(breaks=c(1, 2,3),labels = c("Copartisans", "Non-copartisans","Unaligned"),limits = c(0.5,3.5))+
  scale_y_continuous(limits = c(-0.35,0.35))+
  geom_hline(yintercept = 0,linetype=2, color="grey")+
  geom_hline(yintercept = 0,linetype=2, color="black",size=1.3)+
  geom_vline(xintercept = 1.5,linetype=2, color="grey",size=1.3)+
  labs(x ="Partisanship", y="Average marginal effect of chiefly endorsement")+
  theme_tufte()+
  plottheme+
  facet_wrap(~`Traditional area`)
```

## Gender

```{r}


#| label: main-gender-het
#| results: asis



h2gender_c <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*gender_cat + age + education + total_assets + npp_scale+electoral_area, data=trydat_pr)


h2gender_actual_c <- lm(vote_2020_endorsed ~ treatment_binary*gender_cat + age + education + total_assets + npp_scale+electoral_area, data=trydat_post)


h2gender_c_m <- margins::margins(h2gender_c,data=data.frame(trydat_pr), at = list("gender_cat" =factor(c("Male","Female"))))

sumtab_gender <- summary(h2gender_c_m)[summary(h2gender_c_m)$factor=="treatment_binary", c("gender_cat","AME","SE")]

h2gender_actual_c_m <- margins::margins(h2gender_actual_c,data=data.frame(trydat_post), at = list("gender_cat" =factor(c("Male","Female"))))

sumtab1_gender1 <- summary(h2gender_actual_c_m)[summary(h2gender_actual_c_m)$factor=="treatment_binary", c("gender_cat","AME","SE")]
```

```{r}
#| label: main-gender-het-plot
#| results: asis
#| fig.align: center
#| fig.height: 8
#| fig.width: 10
#| fig.cap: 'Average marginal effect of chiefly endorsement on vote choice by gender'

## Figure F.8



tab_het_gender <- bind_rows(sumtab_gender,sumtab1_gender1)%>%
  dplyr::mutate(Period= c("Pre-election", "Pre-election",  "Post-election", "Post-election"),point=c(0.9,1.9,1.1,2.1))

ggplot(tab_het_gender,mapping = aes(x=point, y=AME, shape=Period))+
  geom_point(size=4)+
  geom_errorbar(mapping=aes(x=point, ymin=AME -1.96*SE, ymax=AME+1.96*SE),size=1,width=.01)+
  scale_x_continuous(breaks=c(1,2),labels = c("Female", "Male"),limits = c(0.5,2.5))+
  scale_y_continuous(limits = c(-0.15,0.25))+
  geom_hline(yintercept = 0,linetype=2, color="grey")+
  geom_vline(xintercept = 1.5,linetype=2, color="grey",size=1.3)+
  labs(x ="Gender of respondent", y="Average marginal effect of chiefly endorsement")+
  theme_tufte()+
  plottheme
```

## Occupation

```{r}

#| label: main-famer-het-plot
#| results: asis
#| fig.align:center
#| fig.height: 8
#| fig.width: 10
#| fig.cap: 'Average marginal effect of chiefly endorsement on vote choice by occupation'

## Figure F.9



h2farmer_c <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*farmer + age + education + total_assets + npp_scale+electoral_area, data=trydat_pr)


h2farmer_actual_c <- lm(vote_2020_endorsed ~ treatment_binary*farmer + age + education + total_assets + npp_scale+electoral_area, data=trydat_post)


h2farmer_c_m <- margins::margins(h2farmer_c,data=data.frame(trydat_pr), at = list("farmer" =factor(c("Other profession","Farmer"))))

sumtab_farmer <- summary(h2farmer_c_m)[summary(h2farmer_c_m)$factor=="treatment_binary", c("farmer","AME","SE")]



h2farmer_actual_c_m <- margins::margins(h2farmer_actual_c,data=data.frame(trydat_post), at = list("farmer" =factor(c("Other profession","Farmer"))))


sumtab1_farmer1 <- summary(h2farmer_actual_c_m)[summary(h2farmer_actual_c_m)$factor=="treatment_binary", c("farmer","AME","SE")]



tab_het_farmer <- bind_rows(sumtab_farmer,sumtab1_farmer1)%>%
  dplyr::mutate(Period= c("Pre-election", "Pre-election",  "Post-election", "Post-election"),point=c(0.9,1.9,1.1,2.1))


ggplot(tab_het_farmer,mapping = aes(x=point, y=AME, shape=Period))+
  geom_point(size=4)+
  geom_errorbar(mapping=aes(x=point, ymin=AME -1.96*SE, ymax=AME+1.96*SE),size=1,width=.01)+
  scale_x_continuous(breaks=c(1,2),labels = c("No", "Yes"),limits = c(0.5,2.5))+
  scale_y_continuous(limits = c(-0.15,0.25))+
  geom_hline(yintercept = 0,linetype=2, color="grey")+
  geom_vline(xintercept = 1.5,linetype=2, color="grey",size=1.3)+
  labs(x ="Respondent is a farmer", y="Average marginal effect of chiefly endorsement")+
  theme_tufte()+
  plottheme
```

## By whether respondent was able to correctly name traditional leader

```{r}

#| label: main-correctchiefname-het-plot
#| results: asis
#| fig.align: center
#| fig.height: 8
#| fig.width: 10
#| fig.cap: 'Average marginal effect of chiefly endorsement on vote choice by occupation'

## Figure F.10


h2namechief_c <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*correctly_name_chief + age + education + total_assets + npp_scale+electoral_area, data=trydat_pr)


h2namechief_actual_c <- lm(vote_2020_endorsed ~ treatment_binary*correctly_name_chief + age + education + total_assets + npp_scale+electoral_area, data=trydat_post)


h2namechief_c_m <- margins::margins(h2namechief_c,data=data.frame(trydat_pr), at = list("correctly_name_chief" =factor(c("No","Yes"))))

sumtab_namechief <- summary(h2namechief_c_m)[summary(h2namechief_c_m)$factor=="treatment_binary", c("correctly_name_chief","AME","SE")]



h2namechief_actual_c_m <- margins::margins(h2namechief_actual_c,data=data.frame(trydat_post), at = list("correctly_name_chief" =factor(c("No","Yes"))))


sumtab1_namechief1 <- summary(h2namechief_actual_c_m)[summary(h2namechief_actual_c_m)$factor=="treatment_binary", c("correctly_name_chief","AME","SE")]


tab_het_namechief <- bind_rows(sumtab_namechief,sumtab1_namechief1)%>%
  dplyr::mutate(Period= c("Pre-election", "Pre-election",  "Post-election", "Post-election"),point=c(0.9,1.9,1.1,2.1))

ggplot(tab_het_namechief,mapping = aes(x=point, y=AME, shape=Period))+
  geom_point(size=4)+
  geom_errorbar(mapping=aes(x=point, ymin=AME -1.96*SE, ymax=AME+1.96*SE),size=1,width=.01)+
  scale_x_continuous(breaks=c(1,2),labels = c("No", "Yes"),limits = c(0.5,2.5))+
  scale_y_continuous(limits = c(-0.15,0.25))+
  geom_hline(yintercept = 0,linetype=2, color="grey")+
  geom_vline(xintercept = 1.5,linetype=2, color="grey",size=1.3)+
  labs(x ="Respondent could correctly name chief", y="Average marginal effect of chiefly endorsement")+
  theme_tufte()+
  plottheme
```

## By whether respondent belong to the majority ethnic group

```{r}

#| label: main-ethnicity-het-plot
#| results: asis
#| fig.align:center
#| fig.height: 8
#| fig.width: 13
#| fig.cap: 'Average marginal effect of chiefly endorsement on vote choice by occupation'

## Figure F.11




##estimates for only Bono

h2bono_c <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*majority_ethnic_bono + age + education + total_assets + npp_scale+electoral_area, data=trydat_pr)


h2bono_actual_c <- lm(vote_2020_endorsed ~ treatment_binary*majority_ethnic_bono + age + education + total_assets + npp_scale+electoral_area, data=trydat_post)


h2bono_c_m <- margins::margins(h2bono_c,data=data.frame(trydat_pr), at = list("majority_ethnic_bono" =factor(c("Bono","Minority group"))))

sumtab_bono <- summary(h2bono_c_m)[summary(h2bono_c_m)$factor=="treatment_binary", c("majority_ethnic_bono","AME","SE")]



h2bono_actual_c_m <- margins::margins(h2bono_actual_c,data=data.frame(trydat_post), at = list("majority_ethnic_bono" =factor(c("Bono","Minority group"))))


sumtab1_bono1 <- summary(h2bono_actual_c_m)[summary(h2bono_actual_c_m)$factor=="treatment_binary", c("majority_ethnic_bono","AME","SE")]



##estimates for only Bono/Asante

h2bonoasante_c <- lm(vote_int_2020_endorsed_voters ~ treatment_binary*majority_ethnic_bono_asante + age + education + total_assets + npp_scale+electoral_area, data=trydat_pr)


h2bonoasante_actual_c <- lm(vote_2020_endorsed ~ treatment_binary*majority_ethnic_bono_asante + age + education + total_assets + npp_scale+electoral_area, data=trydat_post)


h2bonoasante_c_m <- margins::margins(h2bonoasante_c,data=data.frame(trydat_pr), at = list("majority_ethnic_bono_asante" =factor(c("Bono/Asante","Minority group"))))

sumtab_bonoasante <- summary(h2bonoasante_c_m)[summary(h2bonoasante_c_m)$factor=="treatment_binary", c("majority_ethnic_bono_asante","AME","SE")]



h2bonoasante_actual_c_m <- margins::margins(h2bonoasante_actual_c,data=data.frame(trydat_post), at = list("majority_ethnic_bono_asante" =factor(c("Bono/Asante","Minority group"))))


sumtab1_bonoasante1 <- summary(h2bonoasante_actual_c_m)[summary(h2bonoasante_actual_c_m)$factor=="treatment_binary", c("majority_ethnic_bono_asante","AME","SE")]




# Plot for only Bono ethnic group  
tab_het_bono = bind_rows(sumtab_bono,sumtab1_bono1)%>%
  dplyr::mutate(Period= c("Pre-election", "Pre-election",  "Post-election", "Post-election"),point=c(0.9,1.9,1.1,2.1))

p_b <- ggplot(tab_het_bono,mapping = aes(x=point, y=AME, shape=Period))+
  geom_point(size=4)+
  geom_errorbar(mapping=aes(x=point, ymin=AME -1.96*SE, ymax=AME+1.96*SE),size=1,width=.01)+
  scale_x_continuous(breaks=c(1,2),labels = c("Yes", "No"),limits = c(0.5,2.5))+
  scale_y_continuous(limits = c(-0.15,0.25))+
  geom_hline(yintercept = 0,linetype=2, color="grey")+
  geom_vline(xintercept = 1.5,linetype=2, color="grey",size=1.3)+
  labs(x ="Respondent belongs to majority Bono ethnic group", y="Average marginal effect of chiefly endorsement" , title="Panel A: Majority = Bono only")+
  theme_tufte()+
  plottheme


#Plot for Bono/Asante as the main ethnic groups

tab_het_bonoasante = bind_rows(sumtab_bonoasante,sumtab1_bonoasante1)%>%
  dplyr::mutate(Period= c("Pre-election", "Pre-election",  "Post-election", "Post-election"),point=c(0.9,1.9,1.1,2.1))

p_ba <- ggplot(tab_het_bonoasante,mapping = aes(x=point, y=AME, shape=Period))+
  geom_point(size=4)+
  geom_errorbar(mapping=aes(x=point, ymin=AME -1.96*SE, ymax=AME+1.96*SE),size=1,width=.01)+
  scale_x_continuous(breaks=c(1,2),labels = c("Yes", "No"),limits = c(0.5,2.5))+
  scale_y_continuous(limits = c(-0.15,0.25))+
  geom_hline(yintercept = 0,linetype=2, color="grey")+
  geom_vline(xintercept = 1.5,linetype=2, color="grey",size=1.3)+
  labs(x ="Respondent belongs to majority Bono/Asante ethnic group", y="Average marginal effect of chiefly endorsement", title="Panel B: Majority = Bono and Asante")+
  theme_tufte()+
  plottheme


ethplot <- arrangeGrob(p_b, p_ba, ncol = 2)
as_ggplot(ethplot)

```

# Causal mechanisms: effect of chiefly endorsements on intermediate variables

\label{approvemed}

```{r}

mechdat_pr <- master %>%
  dplyr::select(like_nana,trust_nana,agree_local_nana_rev,agree_national_nana_rev,ear_nana_rev,devt_nana_rev,personal_nana_rev, fear, treatment_binary,treatment,age, education, total_assets, npp_scale, electoral_area, party_cluster_collapse3,chief_performance_rate)%>%
  mutate(party_cluster_collapse3 = relevel(party_cluster_collapse3, "NPP"),
         age_cat = factor(ifelse(age >= 18 & age <=35, 1, ifelse(age >= 36 & age <= 55,2,3))),
         app_chief =ifelse(is.na(chief_performance_rate), NA, ifelse(chief_performance_rate>3,1,0)
         ))

mechdat_pr <- na.omit(mechdat_pr)


# rescale variables

mechdat_pr <- dplyr::mutate(mechdat_pr, like_nana_sd = scale(like_nana,center = TRUE),trust_nana_sd=scale(trust_nana),agree_local_nana_rev_sd=scale(agree_local_nana_rev),agree_national_nana_rev_sd=scale(agree_national_nana_rev),ear_nana_rev_sd=scale(ear_nana_rev),devt_nana_rev_sd=scale(devt_nana_rev),personal_nana_rev_sd=scale(personal_nana_rev), fear_sd=scale(fear))



##pre-election: binary

md1 <- lm(like_nana~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,app_chief==1))

md2 <- lm(trust_nana~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,app_chief==1))

md3 <- lm(agree_local_nana_rev~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,app_chief==1))

md4 <- lm(agree_national_nana_rev~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,app_chief==1))

md5 <- lm(ear_nana_rev~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,app_chief==1))

md6 <- lm(devt_nana_rev~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,app_chief==1))

md7 <- lm(personal_nana_rev~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr,app_chief==1))

md8 <- lm(fear~ treatment_binary + age + education + total_assets + npp_scale + electoral_area, data=filter(mechdat_pr, app_chief==1))

mechtab <- rbind(summary(md1)$coef[2, c(1,2,4)],summary(md2)$coef[2, c(1,2,4)],summary(md3)$coef[2, c(1,2,4)],summary(md4)$coef[2, c(1,2,4)],summary(md5)$coef[2, c(1,2,4)],summary(md6)$coef[2, c(1,2,4)],summary(md7)$coef[2, c(1,2,4)],summary(md8)$coef[2, c(1,2,4)])

## means

mn_like <- mean(mechdat_pr$like_nana[mechdat_pr$treatment_binary==0& mechdat_pr$app_chief==1])

mn_trust <- mean(mechdat_pr$trust_nana[mechdat_pr$treatment_binary==0& mechdat_pr$app_chief==1])



mn_locdev <- mean(mechdat_pr$agree_local_nana_rev[mechdat_pr$treatment_binary==0& mechdat_pr$app_chief==1])

mn_natdev <- mean(mechdat_pr$agree_national_nana_rev[mechdat_pr$treatment_binary==0& mechdat_pr$app_chief==1])



mn_earnana <- mean(mechdat_pr$ear_nana_rev[mechdat_pr$treatment_binary==0& mechdat_pr$app_chief==1])

mn_worknana <- mean(mechdat_pr$devt_nana_rev[mechdat_pr$treatment_binary==0& mechdat_pr$app_chief==1])


mn_pers <- mean(mechdat_pr$personal_nana_rev[mechdat_pr$treatment_binary==0& mechdat_pr$app_chief==1])


mn_fear <- mean(mechdat_pr$fear[mechdat_pr$treatment_binary==0& mechdat_pr$app_chief==1])

mn_community <- mean(master$disadv[ mechdat_pr$app_chief==1]==2, na.rm = T)

mn_personal <- mean(master$disadv[ mechdat_pr$app_chief==1]==1, na.rm = T)
  
```

```{r}
#| results: hide

stargazer::stargazer(md1_dt,md3_dt,md4_dt,md5_dt,md6_dt,md7_dt,md8_dt,
  #font.size="scriptsize",
  type = "latex",
  title = "Average ITT effect of chiefly endorsement on intermediate variables",
  dep.var.labels = c("Voted endorsed candidate"),
  covariate.labels = c("Endorsement only", "Endorsement  + rationale","Age" ,"Education", "Total assets", "Closeness to incumbent party (NPP)"),
  multicolumn = T,
  omit = "electoral_area",
  keep.stat = c("n","rsq"),
  notes.align = "l",
  style = "apsr",
  label = "inter_disag",
  header=F
  )
```

# Results of causal mediation analyses

\label{medanalysis}

```{r}
#| label: mech-mechplots
#| fig.align: center
#| fig.height: 14
#| fig.width: 12
#| fig.cap: 'Total, direct, and indirect effects of intermediate variables on vote choice'

## Figure H.1



par(mfrow=c(4,2),mar=c(1, 1, 1, 1))

plot(med_out_like,main="Like and trust the endorsed",cex=3,lwd=3,cex.axis=2, cex.main=1.5)
plot(med_out_loc,main="Endorsed will bring local development",cex=3,lwd=3,cex.axis=2, cex.main=1.5)
plot(med_out_natpol,main="Endorsed will deliver better national policy",cex=3,lwd=3,cex.axis=2, cex.main=1.5)
plot(med_out_ear,main="Endorsed will listen to chief",cex=3,lwd=3,cex.axis=2, cex.main=1.5)
plot(med_out_wdevtch,main="Work well with chief to bring development",cex=3,lwd=3,cex.axis=2, cex.main=1.5)
plot(med_out_per,main="Chief can provide Private benefits",cex=3,lwd=3,cex.axis=2, cex.main=1.5)
plot(med_out_fear,main="Fear of personal or community disadvantage",cex=3,lwd=3,cex.axis=2, cex.main=1.5)
```

```{r}

#| label: mech-mechplots-sensitivity
#| results: asis
#| fig.align: center
#| fig.height: 14
#| fig.width: 12
#| fig.cap: 'Sensitivity analysis of causal mediation analysis'

## Figure H.1




set.seed(45755)

sens.outlike <- medsens(med_out_like, rho.by = 0.1, effect.type = "indirect")

sens.outloc <- medsens(med_out_loc, rho.by = 0.1, effect.type = "indirect")

sens.outnatpol <- medsens(med_out_natpol, rho.by = 0.1, effect.type = "indirect")

sens.outear <- medsens(med_out_ear, rho.by = 0.1, effect.type = "indirect")

sens.outwdevtch <- medsens(med_out_wdevtch, rho.by = 0.1, effect.type = "indirect")

sens.outper <- medsens(med_out_per, rho.by = 0.1, effect.type = "indirect")

sens.outfear <- medsens(med_out_fear, rho.by = 0.1, effect.type = "indirect")

par(mfrow=c(4,2),mar=c(1, 1, 1, 1))

plot(sens.outlike,main="Like and trust the endorsed",cex=3,lwd=3,cex.axis=2, cex.main=1.5)
#plot(sens.outtrust,main="Trust Endorsed")
plot(sens.outloc,main="Endorsed will bring local development",cex=3,lwd=3,cex.axis=2, cex.main=1.5)
plot(sens.outnatpol,main="Endorsed will deliver better national policy",cex=3,lwd=3,cex.axis=2, cex.main=1.5)
plot(sens.outear,main="Endorsed will listen to chief",cex=3,lwd=3,cex.axis=2, cex.main=1.5)
plot(sens.outwdevtch,main="Endorsed will work well with chief to bring local  development",cex=3,lwd=3,cex.axis=2, cex.main=1.5)
plot(sens.outper,main="Chief can provide private benefits",cex=3,lwd=3,cex.axis=2, cex.main=1.5)
plot(sens.outfear,main="Fear of personal or community disadvantage",cex=3,lwd=3,cex.axis=2, cex.main=1.5)
```

\FloatBarrier

```{r}


#| label: mech-mechconfound
#| results: asis
#| fig.align:center
#| fig.height: 14
#| fig.width: 12
#| fig.cap: 'ACME of candidate will "bring local development" with a specified potential confounder. These models assume that the interaction effect between treatment and the primary mediator is constant across individual units (i.e., homogeneous interaction assumption).'

## Figure H.3

## takes 
# set.seed(457546)
# Xnames <- c("age", "education",  "total_assets","npp_scale","electoral_area")
# 
# 
# 
# m.med0 <- multimed(outcome = "vote_int_2020_endorsed_voters", med.main = "agree_local_nana_rev", med.alt = "like_trust_nana", treat = "treatment_binary", covariates = Xnames, data = mechdat_pr_opp, sims = 1000)
# 
# 
# m.med1 <- multimed(outcome = "vote_int_2020_endorsed_voters", med.main = "agree_local_nana_rev", med.alt = "agree_national_nana_rev", treat = "treatment_binary", covariates = Xnames, data = mechdat_pr_opp, sims = 1000)
# 
# 
# m.med2 <- multimed(outcome = "vote_int_2020_endorsed_voters", med.main = "agree_local_nana_rev", med.alt = "ear_nana_rev", treat = "treatment_binary", covariates = Xnames, data = mechdat_pr_opp, sims = 1000)
# 
# 
# 
# 
# m.med3 <- multimed(outcome = "vote_int_2020_endorsed_voters", med.main = "agree_local_nana_rev", med.alt = "devt_nana_rev", treat = "treatment_binary", covariates = Xnames, data = mechdat_pr_opp, sims = 1000)
# 
# 
# m.med4 <- multimed(outcome = "vote_int_2020_endorsed_voters", med.main = "agree_local_nana_rev", med.alt = "personal_nana_rev", treat = "treatment_binary", covariates = Xnames, data = mechdat_pr_opp, sims = 1000)
# 
# 
# m.med5 <- multimed(outcome = "vote_int_2020_endorsed_voters", med.main = "agree_local_nana_rev", med.alt = "fear", treat = "treatment_binary", covariates = Xnames, data = mechdat_pr_opp, sims = 1000)



tabconf <- tibble(
  estimates = c(0.06747,0.03393,0.04243,0.06471,0.064246,0.06507,0.06340),
  lb=c(0.01543,-0.00174,0.00141,0.00952,0.010313,0.01015,0.00807),ub=c(0.12,0.07,0.08,0.12,0.12,0.12,0.12),
  pt=1:7
)


ggplot(tabconf,mapping = aes(x=pt, y=estimates))+
   geom_point(size=4)+
   geom_errorbar(mapping=aes(x=pt, ymin=lb, ymax=ub),size=1.5,width=.01)+
  scale_x_continuous(breaks=c(1:7),labels = c("Unadjusted ACME", "Likable and trustworthy", "National \npolicy","Endorsed will listen to chief","Endorsed will \nwork well with chief \n for local development", "Chief can provide \n private benefits","Fear of personal \n or community disadvantage"),limits = c(0.5,7.5))+
  scale_y_continuous(limits = c(-0.05,0.15))+
  geom_hline(yintercept = 0,linetype=2, color="black",size=2)+
  geom_vline(xintercept = 1.5,linetype=2, color="black",size=2)+
  labs(x ="Specified potential confounder", y="ACME",title = "")+
  theme_tufte()+
  plottheme


```
